简体   繁体   中英

Python How to override a class member in the child and access it from parent?

So in Python I have one class like this:

class Parent(object):
    ID = None

    @staticmethod
    def getId():
        return Parent.ID

Then I override the ID in a child class, like this:

class Child(Parent):
    ID = "Child Class"

Now I want to call the getId() method of the child:

ch = Child()
print ch.getId()

I would like to see "Child Class" now, but instead I get "None".
How can I achive that in Python?

PS: I know I could access ch.ID directly, so this may be more a theoretical question.

Use a class method:

class Parent(object):
    ID = None

    @classmethod
    def getId(cls):
        return cls.ID

class Child(Parent):
    ID = "Child Class"

print Child.getId() # "Child Class"

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