The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:
self.data = 
When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:
|class DerivedClassName(Base1, Base2, Base3):
For new-style classes, the method resolution order changes dynamically to support cooperative calls to super(). This approach is known in some other multiple-inheritance languages as call-next-method and is more powerful than the super call found in single-inheritance languages.
*args and **kwargs
Putting *args and/or **kwargs as the last items in your function definition’s argument list allows that function to accept an arbitrary number of anonymous and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could write it like this:
It’s probably more commonly used in object-oriented programming, when you’re overriding a function, and want to call the original function with whatever arguments the user passes in.
You don’t actually have to call them args and kwargs, that’s just a convention. It’s the * and ** that do the magic.
|class Super( object ):
def __init__( self, this, that ):
self.this = this
self.that = that
class Sub( Super ):
x= Super( 2.7, 3.1 )
This way Sub doesn’t really know (or care) what the superclass initialization is. Should you realize that you need to change the superclass, you can fix things without having to sweat the details in each subclass.
you can also call functions with *mylist and **mydict to unpack positional and keyword arguments:
|def foo(a, b, c, d):
print a, b, c, d
l = [0, 1]
Will print: 0 1 2 3
… x = int(raw_input(“Please enter a number: “))
… except ValueError:
… print “Oops! That was no valid number. Try again…”
|for arg in sys.argv[1:]:
f = open(arg, ‘r’)
print ‘cannot open’, arg
print arg, ‘has’, len(f.readlines()), ‘lines’
The raise statement allows the programmer to force a specified exception to occur. For example:
An empty file that tells Python that this directory should be considered a Python package. (Readmore about packages in the official Python docs if you’re a Python beginner.)