Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 312
Matthias Avatar asked Mar 22 '23 23:03

Matthias


1 Answers

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"
like image 74
user278064 Avatar answered Apr 25 '23 19:04

user278064