[英]Python How to override a class member in the child and access it from parent?
所以在Python中我有一個這樣的類:
class Parent(object):
ID = None
@staticmethod
def getId():
return Parent.ID
然后我覆蓋子類中的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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.