Inheritance from the parent class - Python

I am learning all the Python classes, and I have many opportunities for coverage. I came across an example that confused me a bit.

These are parent classes.

Class X
Class Y
Class Z

Classes for children:

Class A (X,Y)
Class B (Y,Z)

Grandchild Class:

Class M (A,B,Z)

Does not Class Minherit Class Zthrough inheritance from Class Bor what will be the reason for this type of structure? Class Mwill just ignore the second time Class Zinherited, right, or am I missing something?

+4
source share
2 answers

Class M just inherits the attributes of class Z twice (redundantly), right, or am I missing something?

, "" , Python , (MRO), , , . , Z .

MRO , :

MRO(X) = (X,object)
MRO(Y) = (Y,object)
MRO(Z) = (Z,object)

MRO(A) = (A,X,Y,object)
MRO(B) = (B,Y,Z,object)

MRO M :

MRO(M) = (M,)+merge((A,X,Y,object),(B,Y,Z,object),(Z,object))
       = (M,A,X,B,Y,Z,object)

, , Python , self.__dict__ ). , Python MRO . .

super() - -, , MRO . , :

class B:

    def foo():
        super().bar()

m = M() m.foo(), - foo() B, super().bar bar Y, , bar Z , , object.

. , :

self.qux = 1425

self.__dict__ .

Z, , : B , Z . , Z - MRO, B .

+7

, @Willem, , . python, , Java. : - ( __new__) ( __init__). , , . child , ().

>>> class A(object): 
      def __init__(self): 
         self.a = 23
>>> class B(A): 
      def __init__(self): 
         self.b = 33
>>> class C(A): 
      def __init__(self): 
         self.c = 44 
         super(C, self).__init__()
>>> a = A()
>>> b = B()
>>> c = C()
>>> print (a.a) 23
>>> print (b.a) Traceback (most recent call last):   File "<stdin>", line 1, in <module> AttributeError: 'B' object has no attribute 'a'
>>> print (c.a) 23

, B A __init__, -, , A. , Java, , . .

, , __dict__ __getattribute__ , mro, willem. vars() dir() .

+2

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


All Articles