I'm learning the Python programming language and I've came across something I don't fully understand.
In a method like:
def method(self, blah):
def __init__(?):
....
....
What does self
do? What is it meant to be? Is it mandatory?
What does the __init__
method do? Why is it necessary? (etc.)
I think they might be OOP constructs, but I don't know very much.
A brief illustrative example
In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an
__init__
function:note that
self
could actually be any valid python identifier. For example, we could just as easily write, from Chris B's example:and it would work exactly the same. It is however recommended to use self because other pythoners will recognize it more easily.
Had trouble undestanding this myself. Even after reading the answers here.
To properly understand the
__init__
method you need to understand self.The self Parameter
The arguments accepted by the
__init__
method are :But we only actually pass it two arguments :
Where has the extra argument come from ?
When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs.
In order to access object attributes from within the
__init__
method we need a reference to the object.Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self.
This means in the
__init__
method we can do :Here we are setting attributes on the object. You can verify this by doing the following :
values like this are known as object attributes. Here the
__init__
method sets the arg1 and arg2 attributes of the instance.source: http://www.voidspace.org.uk/python/articles/OOP.shtml#the-init-method
Just a demo for the question.
In this code:
Here
__init__
acts as a constructor for the class and when an object is instantiated, this function is called.self
represents the instantiating object.The result of the above statements will be as follows:
__init__
is basically a function which will "initialize"/"activate" the properties of the class for a specific object, once created and matched to the corresponding class..self
represents that object which will inherit those properties.