class A:
def __init__(self):
print 'A'
class B(A):
def __init__(self):
print 'B'
b = B()
B
In C++, I would have expected to see A B
output, but in Python I am getting only B
. I know that I can do super(B, self).__init__()
to achieve the same in Python, but as this is apparently not the default (or is it - I am new to the syntax as well), I am worried that the paradigms for instatinating objects are completely different.
So what are objects in Python, what is their relation with classes and what is the standard way to initialize all data in all parent classes in Python?
That depends on what you mean by "use." If you mean, does the default constructor for a child class call the parent constructor, then yes, it does (more below). If you mean, is a default constructor matching whatever parameters the parent constructor has created automatically, then no, not in the general case.
Before you can initialize an object in a constructor, the object's parent constructor must be called first. If you don't write an explicit call to the super() constructor, Java automatically inserts one in your constructor. The compiler automatically inserts superclass constructor calls in both constructors.
If the child class constructor does not call super , the parent's constructor with no arguments will be implicitly called. If parent class implements a constructor with arguments and has no a constructor with no arguments, then the child constructors must explicitly call a parents constructor.
In simple words, a constructor cannot be inherited, since in subclasses it has a different name (the name of the subclass). Methods, instead, are inherited with "the same name" and can be used.
Python rarely does anything automatically. As you say, if you want to invoke the superclass __init__
, then you need to do it yourself, usually by calling super
:
class B(A):
def __init__(self):
print 'B'
super(B, self).__init__()
The point to note is that instance attributes, like everything else in Python, are dynamic. __init__
is not the constructor, that's __new__
which you rarely need to meddle with. The object is fully constructed by the time __init__
is called, but since instance attributes are dynamic they are usually added by that method, which is only special in that it's called first once the object is created.
You can of course create instance attributes in any other method, or even from outside the class itself by simply doing something like myBobj.foo = 'bar'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With