简体   繁体   English

从父类执行时父类实例变量被覆盖

[英]Parent class instance variable getting overridden when executing from the parent class

class Foo:

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


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



class Bar(Foo):
    def __init__(self):
        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 Foo B 类中的模型

Model in class Bar B B类酒吧模特

Why is the variable model in class Foo getting overridden when it is in the parent class.为什么类Foo中的变量模型在父类中时会被覆盖。 Is this what should really happen?这真的应该发生吗? I want to make it the print A when it is executing from the parent class.当它从父类执行时,我想让它成为打印A。 What's going wrong here in the code代码中出了什么问题

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此行执行 Class Bar的初始化程序,从这一刻起bar.model指向字符串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 .当您调用父类方法时,它确实被执行了(您可以通过 print 的输出观察到),但这并没有改变对象bar的属性model的值。

Why is the variable model in class Foo getting overridden when it is in the parent class.为什么类 Foo 中的变量模型在父类中时会被覆盖。 Is this what should really happen?这真的应该发生吗?

The variable model defined in the class Foo is not getting overridden, in fact it's never being set in the base class. Foo类中定义的变量模型不会被覆盖,实际上它从未在基类中设置。

I want to make it the print A when it is executing from the parent class当它从父类执行时,我想让它成为 print A

Then you need to change your constructor:然后你需要改变你的构造函数:

class Bar(Foo):
    def __init__(self):
        super().__init__()


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM