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.

3
  • 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). Commented Jan 29, 2018 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...") Commented Jan 29, 2018 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. Commented Jan 29, 2018 at 17:52

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.