Why aren't parent constructors called when instantiating the class?

class A: def __init__(self): print 'A' class B(A): def __init__(self): print 'B' b = B() B 

In C ++, I expected to see AB output, but in Python I only get B I know I can do super(B, self).__init__() to achieve the same thing in Python, but since this is apparently not the default (or is this I am also new to the syntax), I'm worried the fact that the paradigm for creating objects is completely different.

So, what are objects in Python, what is their relationship to classes, and what is the standard way to initialize all the data in all parent classes in Python?

+4
source share
3 answers

So what are the objects in Python

Well, objects in python are like member and method dictionaries. It is no harder than that. You do not have visibility processing (if you want to hide the participant, just do not talk about it in the public documentation, only with a comment).

what is their relationship with classes

The class defines the skeleton of the method / member that will instantiate this dict / object. So you got the __init__() constructor, which is the only handler used to create this object.

What is the standard way to initialize all data in all parent classes in Python?

Either you do not override the constructor, and then all the parent classes initiate your constructor (for example, the default C ++ behavior) or you override the constructor, and then you must make an explicit call to the constructor of the parent class.

Remember zen python: "Explicit is better than implicit." It is fully applicable here.

+2
source

Python rarely does anything automatically. As you say, if you want to call the __init__ superclass, you need to do it yourself, usually by calling super :

 class B(A): def __init__(self): print 'B' super(B, self).__init__() 

It should be noted that instance attributes, like everything else in Python, are dynamic. __init__ not a constructor, which is __new__ , with which you rarely have to intervene. The object is completely built in time when __init__ is called, but since the attributes of the instance are dynamic, they are usually added by this method, which is special only in that it is called first as soon as the object is created.

Of course, you can create instance attributes in any other method, or even outside the class, just by doing something like myBobj.foo = 'bar' .

+4
source

You need to call the base constructor in your inherited class constructor:

 class B(A): def __init__(self): A.__init__(self) # super(B, self).__init__() you can use this line as well print 'B' 
+1
source

Source: https://habr.com/ru/post/1485774/


All Articles