user103716
user103716

Reputation: 312

python circular inheritance, overwriting class declarations

Trying to understand how Python creates some classes

class A:
    pass

class B(A):
    pass

class A(B):
    pass

a = A()

I was expecting some error because of the circular dependency, but it doesn't complain.

A.__mro__ prints (__main__.A, __main__.B, __main__.A, object)

so it looks like there are two classes called A. I was expecting the second declaration to overwrite the first one.

Can anyone explain in detail what is happening here? is the first A class reachable at all?

Upvotes: 0

Views: 110

Answers (1)

khelwood
khelwood

Reputation: 59113

There is no circular inheritance: You created three classes. The first is the base class of the second, and the second is the base class of the third. The third one was given the same name as the first one (A), so the global name A now refers to the third one. Just like reassigning a variable.

And yes, the first one is reachable because, as you already pointed out, it's in A.__mro__. So if you wanted, you could do:

old_A = A.__mro__[2]

Upvotes: 2

Related Questions