To understand the role of __init__(self, ...)
you have to understand classes first.
A class basically defines a type of object. For example, if I wanted to define how a Fish
behaves, I might start out with something of the form
class Fish:
def swim(self):
print "I'm swimming!"
def breathe(self):
print "I'm breathing!"
However, that's not a very useful class because, while we've defined what a Fish
can do, we don't know how to store other essential qualities about the Fish
, e.g. how heavy it is.
In principle, if I have a Fish
named f
, I could just do
f.weight = 3
But if I forget to do that for some Fish
, say a Fish
named g
, and then try to use g.weight
in an expression, Python won't be very happy - it'll throw an AttributeError
complaining that Fish instance has no attribute 'weight'
.
To avoid that, we can define a constructor for our class that, every time a new Fish
is created, sets properties like its weight and its color and whatever else you define to sensible default values. In Python, this constructor function is called __init__
. As long as you define it in a class, it will be called every time a new instance of that class is created.
class Fish:
def __init__(self):
self.weight = 3
def swim(self):
print "I'm swimming!"
def breathe(self):
print "I'm breathing!"
Every function you define for a class takes an implied argument, which we usually label as self
. This first argument is always set to the instance on which you're calling the function. For instance, if I invoke
f = Fish()
f.swim()
Python creates a Fish
, puts it in f
, then calls Fish.__init__(f)
and Fish.swim(f)
on it. In this case, the Fish
in f
will have its weight set to 3 and will cause "I'm swimming!" to be printed.
You can create class functions that don't need to take the self
argument, called static functions, but those are useful only for specific cases you probably won't encounter for a while. Class functions in Python will usually be instance functions, which will take the self
argument implicitly.
Note that, in the above example, every Fish
created will have its default weight set to 3. What if we want to specify a Fish
's weight at the time of creation? Well, we can define __init__()
to take some extra arguments:
class SuperFish:
def __init__(self, weight = 3):
self.weight = weight
Note that the weight
argument has a default value defined as 3. Thus, it is in fact optional for us to specify the weight. If we had just said def __init__(self, weight):
instead, then specifying the weight would be required.
We can now perform any one of the following invocations:
a = SuperFish() # creates a SuperFish with a weight of 3
b = SuperFish(42) # creates a SuperFish with a weight of 42
c = SuperFish(weight = 9001) # creates a SuperFish with a weight of 9001
Hope that clears things up for you :)