Reputation: 10379
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.
Upvotes: 4
Views: 157
Reputation: 10170
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"
Upvotes: 7