Python How do I override a class member in a child and access it from a parent?

So in Python, I have one class:

class Parent(object):
    ID = None

    @staticmethod
    def getId():
        return Parent.ID

Then I redefine the identifier in the child class, for example:

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

Now I want to call a method getId()for a child:

ch = Child()
print ch.getId()

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

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

+4
source share
1 answer

Use 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"
+7
source

All Articles