所以在 Python 中我有这样一个类:
class Parent(object):
ID = None
@staticmethod
def getId():
return Parent.ID
然后我在子类中覆盖 ID,如下所示:
class Child(Parent):
ID = "Child Class"
现在我要调用child的getId()
方法:
ch = Child()
print ch.getId()
我现在想看到“子类”,但我得到的却是“无”。
我怎样才能在 Python 中实现它?
PS:我知道我可以直接访问ch.ID
,所以这可能更像是一个理论问题。
最佳答案
使用类方法:
class Parent(object):
ID = None
@classmethod
def getId(cls):
return cls.ID
class Child(Parent):
ID = "Child Class"
print Child.getId() # "Child Class"
关于Python 如何覆盖子类中的类成员并从父类访问它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19467099/