[英]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.