[英]Python How to override a class member in the child and access it from parent?
So in Python I have one class like this: 所以在Python中我有一个这样的类:
class Parent(object):
ID = None
@staticmethod
def getId():
return Parent.ID
Then I override the ID in a child class, like this: 然后我覆盖子类中的ID,如下所示:
class Child(Parent):
ID = "Child Class"
Now I want to call the getId()
method of the child: 现在我想调用子
getId()
方法:
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? 我怎样才能在Python中实现这一目标?
PS: I know I could access ch.ID
directly, so this may be more a theoretical question. PS:我知道我可以直接访问
ch.ID
,所以这可能更像是一个理论问题。
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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.