The fact is that in python there is a clear distinction between class and instance attributes:
Attributes declared in the class body, outside any method, are class attributes, they are the same for each object of that class and are the ones that are inherited by the subclasses. Be aware of the fact that doing instance_obj.class_att = something
doesn't change the value of the class attribute, but simply creates an instance attribute and hides the shared class attribute for that object.
Instance attributes are the ones that are declared with syntax instance_obj.att = something
, they are not shared between instances and are the most similar thing to non-static attributes that you have in other programming languages and they are usually created in the init method.self
is just a convention to indicate the instance object automatically passed to methods.
Here's an example:
class MyClass:
c = 1 #class attribute, the subclasses will inherit this
def __init__(self):
self.i = 1 #instance attribute
MyClass.c #access attribute c of class MyClass
MyClass.i #error! MyClass has no attribute i
x = MyClass() #calling __init__ creates instance attribute i for obj x
x.i #access instance attribute i of object x
x.c #access class attribute c of class MyClass
x.c = 2 #hide MyClass.c and create instance attribute c for obj x
x.c #access instance attribute c of obj x
So, to sum up, doing:
class y(x):
def __init__(self):
x.__init__(self)
is useful because if the base class would have been something like this
class x:
def __init__(self):
self.i=1
you would have not been able to access the attribute i from any instances of y simply because they would not have it.