self
is the object you're calling the method on. It's a bit like this
in Java.
__init__
is called on each object when it is created to initialise it. It's like the constructor in Java.
So you would use __init__
whenever you wanted to set any attributes - member variables in Java - of the object when it was created. If you're happy with an "empty" object you don't need an __init__
method but if you want to create an object with arguments you'll need one.
An example would be:
class StackOverflowUser:
def __init__(self, name, userid, rep):
self.name = name
self.userid = userid
self.rep = rep
dave = StackOverflowUser("Dave Webb",3171,500)
We can then look at the object we've created:
>>> dave.rep
500
>>> dave.name
'Dave Webb'
So we can see __init__
is passed the arguments we gave to the constructor along with self
, which is the reference to the object that has been created. We then use self
when we process the arguments and update the object appropriately.
There is the question of why Python has self
when other languages don't need it. According to the Python FAQ:
Why must 'self' be used explicitly in method definitions and calls?
First, it's more obvious that you are using a method or instance attribute instead of a local variable...
Second, it means that no special syntax is necessary if you want to explicitly reference or call the method from a particular class...
Finally, for instance variables it solves a syntactic problem with assignment: since local variables in Python are (by definition!) those variables to which a value assigned in a function body (and that aren't explicitly declared global), there has to be some way to tell the interpreter that an assignment was meant to assign to an instance variable instead of to a local variable, and it should preferably be syntactic (for efficiency reasons)...