0

I read Python's documentation and can't understand this piece of information

class DerivedClassName(Base1, Base2, Base3):
    <statement-1>
    .
    .
    .
    <statement-N>

For most purposes, in the simplest cases, you can think of the search for attributes inherited from a parent class as depth-first, left-to-right, not searching twice in the same class where there is an overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched for in Base1, then (recursively) in the base classes of Base1, and if it was not found there, it was searched for in Base2, and so on.

If it is new-style class, why does Python search recursively in the base classes of Base1 and not going to Base2 then Base3?

class A(object): 
    attr = 1

class B(A):
    pass
class C(A):
    attr = 2
class D(B,C):
    pass
x = D() 
print(x.attr)# 2

Sample from Mark Lutz's book. Python goes to D then B then C.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Timothy
  • 21
  • 1
    It's not clear why you think your example disagrees with the description. Also, please use appropriate block quote formatting to clarify what is a quote (and include specifically from where). – jonrsharpe Jan 29 '18 at 17:44
  • 3
    Are you asking why `C` comes before `A` in the resolution order? If so, the answer is that the order _isn't_ just a depth first search in Python 3. (Hence the hedging: _"For most purposes, in the simplest cases, you can think of..."_ Also hence the next line after your quote: _"In fact, it is slightly more complex than that..."_) – glibdud Jan 29 '18 at 17:52
  • That's the tutorial. It says "*For most purposes*, *in the simplest cases*, you can *think of* the search for attributes inherited from a parent class as...". It is obviously not trying to say that the description is completely accurate or general. – user2357112 Jan 29 '18 at 17:52

2 Answers2

1

If you continue to read, then the documentation says "In fact, it is slightly more complex than that". The thing you mention is oriented to single inheritance language. Python works different, and they implemented super(). You can either read on the documentation to know how does it work, or/and (depends on your level of curiosity) you can go read the answer on here and start playing with the code and see what happens.

Good Luck

jtagle
  • 302
  • 1
  • 8
1

Attribute lookup occurs according to the method resolution order (MRO) established when the class is first defined. One important rule of the MRO is that no class appears before any of its children. This means the MRO for D is [D, B, C, A, object], not [D, B, A, object, C] as you would expect from a pure depth-first search.

chepner
  • 497,756
  • 71
  • 530
  • 681