[英]How to access class attributes of a derived class in the base class in Python3?
I want to do something in a base class ( FooBase
) with the class attribues of the derived classes ( Foo
). 我想在基类( FooBase
)中使用派生类( Foo
)的类属性进行操作。 I want to do this with Python 3 . 我想用Python 3做到这一点。
class BaseFoo:
#felder = [] doesn't work
def test():
print(__class__.felder)
class Foo(BaseFoo):
felder = ['eins', 'zwei', 'yep']
if __name__ == '__main__':
Foo.test()
Maybe there is a different approach to this? 也许有不同的方法吗?
You need to make test
a class method , and give it an argument that it can use to access the class; 您需要将test
作为一个类方法 ,并为其提供一个可用于访问该类的参数。 conventionally this arg is named cls
. 通常,此arg称为cls
。
class BaseFoo:
@classmethod
def test(cls):
print(cls.felder)
class Foo(BaseFoo):
felder = ['eins', 'zwei', 'yep']
if __name__ == '__main__':
Foo.test()
output 输出
['eins', 'zwei', 'yep']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.