Search code examples
python-3.xclassredefinition

Python3 redefine a class: super still calls old class


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.


Solution

  • 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.