如何访问 Python3 中基 class 派生 class 的 class 属性?

How to access class attributes of a derived class in the base class in Python3?

我想在基础 class (FooBase) 中使用派生 class 的 class 属性 做一些事情]es(Foo)。我想用 Python3.

来做到这一点
class BaseFoo:
   #felder = [] doesn't work

   def test():
      print(__class__.felder)

class Foo(BaseFoo):
   felder = ['eins', 'zwei', 'yep']


if __name__ ==  '__main__':
    Foo.test()

也许对此有不同的方法?

您需要将 test 设为 class method,并为其提供可用于访问 class 的参数;按照惯例,这个 arg 被命名为 cls.

class BaseFoo:
    @classmethod
    def test(cls):
        print(cls.felder)

class Foo(BaseFoo):
    felder = ['eins', 'zwei', 'yep']


if __name__ ==  '__main__':
    Foo.test()

输出

['eins', 'zwei', 'yep']