Python3 redefine a class: super still calls old class

37 Views Asked by At

This code:

class a:
    def __init__(self):
        print("a here")

class b(a):
    def __init__(self):
        print("b here")
        super().__init__()

B = b()

class a:
    def __init__(self):
        print("NEW a here")

BB = b()

produces this output:

b here
a here
b here
a here

Why?

If I change the super().init() in class b to a.init(self), it works correctly.

2

There are 2 best solutions below

0
Blckknght On BEST ANSWER

Class b holds a reference to its base class(es). That reference is created when the class is created, not looked up by name later on when super gets called. Thus, the "incorrect" behavior that you're seeing is actually the expected behavior. To change what class b sees as its base class, you need to redefine b too.

0
spacether On

I think that this is happening because class b is still inheriting from the original class a that you defined. You can check this by printing out the ids of the a classes

id(a)
id(b.__bases__[0])