简体   繁体   English

在子类的父级中访问覆盖的类变量

[英]Access overridden class variable in parent of subclass

How to I access a class variable that I expect a subclass to replace? 如何访问我希望替换子类的类变量?

this is what i want to acchieve: 这是我要实现的目标:

class Foo():
    var = "Foo"
    @staticmethod
    def print_var():
    print(Foo.var)

class Bar(Foo):
    var = "Bar"

>> Bar.print_var()
>> "Bar

The code above prints "Foo" instead of "Bar" 上面的代码显示“ Foo”而不是“ Bar”

Don't use staticmethod . 不要使用staticmethod At the very least use @classmethod decorator here: 至少在这里使用@classmethod装饰器

class Foo():
    var = "Foo"

    @classmethod
    def print_var(cls):
        print(cls.var)

class Bar(Foo):
    var = "Bar"

This makes print_var accessible on the class, but is passed a reference to the current class so you can look up var on the 'right' object. 这使得在print_var可以访问print_var ,但是传递了对当前类的引用,因此您可以在“正确的”对象上查找var

Use staticmethod only if you want to remove all context from a method, turning it into a regular function again. 仅当要从方法中删除所有上下文,然后再次将其转换为常规函数时,才使用staticmethod

Demo: 演示:

>>> class Foo():
...     var = "Foo"
...     @classmethod
...     def print_var(cls):
...         print(cls.var)
... 
>>> class Bar(Foo):
...     var = "Bar"
... 
>>> Bar.print_var()
Bar
>>> Foo.print_var()
Foo

Use a classmethod : 使用classmethod

class Foo():
    @classmethod
    def print_var(cls):
        print(cls.var)

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

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