Home > Software design >  Python3 redefine a class: super still calls old class
Python3 redefine a class: super still calls old class

Time:12-03

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.

CodePudding user response:

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.

CodePudding user response:

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])

  • Related