Reputation: 8042
As the title suggests, I am struggling to understand the true purpose of the init constructor in Python and specifically when we create a class that inherits from another (parent). Having gone through "diveintopython", I am a bit confused as to what exactly happens when class B inherits from A.
In the following example (taken from here: What is the purpose of calling __init__ directly?)
class A:
def __init__(self, x):
self.x = x
class B(A):
def __init__(self, x, y):
A.__init__(self, x)
self.y = y
What exactly happens if we don't make the call to the parent init A.__init__(self, x)
?
Will attribute x still exist in class B?
Furthermore, shouldn't Class B(A)
already entail the call to parent init?
In other words are we allowed to skip the call, and if we do which would be the consequences?
Upvotes: 0
Views: 145
Reputation: 12116
If you don't make the call to __init__
, then no, x
will not exist on that instance of class B
. A.__init__
will not be run because you never called it!
class B(A)
means that B
inherits from A
, but it doesn't automagically call the constructor of A
when you make an instance of B
. This means that you can control whether you want it yourself - you generally should be calling the constructor, but it's your choice whether you want to or not. The consequences depend on the class you're subclassing - there may be no problems, or your code may not work at all. In this case, as I've said, if you skip the call to A.__init__
and then try
b = B()
print(b.x)
you'll get an exception.
Just as a general note, you don't have to name the superclass when calling its __init__
- you can use super(B, self).__init__(x)
or just super().__init__(x)
in Python 3.
Upvotes: 2
Reputation: 239443
__init__
is called only after the object is created in memory, unlike C++. So, its true purpose is to initialize/create instance variables only.
If you don't call the parent's __init__
, it will not create the variable x
. See, what we are passing as the first parameter to the parent's __init__
call. We pass the current object (self
). Now, the parent's __init__
, creates the variable x
on the child's object.
Upvotes: 2