Home > Blockchain >  Parent class instance variable getting overridden when executing from the parent class
Parent class instance variable getting overridden when executing from the parent class

Time:12-24

class Foo:

    def __init__(self):
        self.model = 'A'


    def create(self):
        print(f'Model in class {self.model}')



class Bar(Foo):
    def __init__(self):
        super().__init__()
        self.model = 'B'


    def save(self):
        super().create()

        print(f'Model in class Bar {self.model}')


bar = Bar()
bar.save()

Output:

Model in class Foo B

Model in class Bar B

Why is the variable model in class Foo getting overridden when it is in the parent class. Is this what should really happen? I want to make it the print A when it is executing from the parent class. What's going wrong here in the code

CodePudding user response:

Why is the variable model in class Foo getting overridden when it is in the parent class.

Because that self parameter in the create() method is bound to the instance of the Bar. So it first checks the bar's dictionary and yes there is a model attribute which has the value of "B". Insert a simple print statement to check that:

    def create(self):
        print(self)
        print(f'Model in class {self.model}')

And why its value is "B" and not "A"? Because the order of calling super().__init__() and self.model = 'B' matters. If you change the order it has the value of "A". Again add a simple print statement between these two and you'll see it prints "A":

class Bar(Foo):
    def __init__(self):
        super().__init__()
        print(self.model)
        self.model = 'B'

CodePudding user response:

Nothing is wrong. Everything works as expected. This line executes initializer of Class Bar and from this moment bar.model is pointing to string B

bar=Bar()

When you call the parent class method it is indeed executed (what you can observe by the output of print), but this doesn't change the value of attribute model of object bar.

Disclaimer!

Since you are making edits to the question this answer will soon make no sense neither... If you call super().create directly below thesuoer().__init__() call and BEFORE the assignment to self.model you can see the desired behaviour.

  • Related