简体   繁体   中英

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 ). I want to do this with 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; conventionally this arg is named 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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