【问题标题】:Change reference of class level variable更改类级别变量的引用
【发布时间】:2021-12-06 11:14:17
【问题描述】:

我们有一个班级:

class Parent:
    A = 1

def print_a(self):
   print(Parent.A)

我想创建另一个继承第一个类并更改类变量:

class Child(Parent):
    A = 2

现在,当我执行时:

example = Child()
example.print_a()

它打印“1”。

如何更改子类中类变量 A 的引用(在 print_a 函数中)?我不想复制替换 Parent.A 的整个 print_a 函数。

重要的是,在这种情况下我无法编辑父类。

【问题讨论】:

    标签: python oop inheritance


    【解决方案1】:

    你必须使用@classmethod 装饰器

    这应该可以按预期工作:

    class Parent:
        A = 1
    
        @classmethod
        def print_a(cls):
            print(cls.A)
    
    
    class Child(Parent):
        A = 2
    
    if __name__ == '__main__':
        Child.print_a()
        e = Child()
        e.print_a()
     
        # Child.A is not inherited from parent
        Parent.print_a()
    

    输出:

    2
    2
    1
    

    如果要在父级中设置变量:

    
    class Child(Parent):
        Parent.A = 2
    

    【讨论】:

    • 我无法编辑父类。也许,还有其他一些方法可以创建 Parent 类的实例并更改 A 吗?
    • 就像我展示的那样,您可以在Child 中使用Parent.A=2 更改它。那么你的原始代码应该可以工作了。
    • 问题是如果我们有 Parent 类的实例,Parent.A = 2 会影响它们..
    • 你也可以覆盖子类中的 print_a 方法(也许让它成为父类应该的@classmethod)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 2023-02-14
    • 2014-10-22
    相关资源
    最近更新 更多