Python如何重写子级中的类成员并从父级访问它?
因此,在Python中,我有一个类如下:Python如何重写子级中的类成员并从父级访问它?,python,class,inheritance,Python,Class,Inheritance,因此,在Python中,我有一个类如下: class Parent(object): ID = None @staticmethod def getId(): return Parent.ID class Child(Parent): ID = "Child Class" 然后我重写子类中的ID,如下所示: class Parent(object): ID = None @staticmethod def getId
class Parent(object):
ID = None
@staticmethod
def getId():
return Parent.ID
class Child(Parent):
ID = "Child Class"
然后我重写子类中的ID,如下所示:
class Parent(object):
ID = None
@staticmethod
def getId():
return Parent.ID
class Child(Parent):
ID = "Child Class"
现在我想调用子对象的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"