[英]How to enforce a subclass to implement a parent class' abstract methods using __init_subclass__ instead of ABCMeta?
[英]How to access Parent class methods in subclass
類“ X”是父類,類“ Y”是X的子類。類Y的子類如何訪問作為其父類的類X。
class x:
def __init__(self,text):
self.text = t
def printThis(self):
text = self.text
print(text)
class y(x):
def test():
printThis(text)
a = y("printing")
a.printThis()
Y類的子類如何訪問其父類的類X。
Python具有多重繼承,因此一個類可能擁有多個父類。 所有這些都由“ mro”(方法順序解析)和super()
對象處理 ,您可以從mro中的“ next”類訪問方法。
現在請注意,在代碼段中,真正的問題根本不是“訪問父類”,而是您正在嘗試訪問全局 “ printThis”名稱-未定義。 Python沒有像Java這樣的“隱式表示”,您必須使用self
來引用實例屬性或方法,因此您需要的是:
class Y(X):
def test(self):
self.printThis()
為了說明這一點與父類無關,在同一個類中沒有self
的情況下調用printThis()
相同的問題:
class Example():
def __init__(self, text):
self.text = text
def printThis(self):
print(self.text)
def test(self):
# this will fail just as well
printThis()
另外,這里不需要super()
,Python會在定義此名稱的mro的第一個類上解析printThis
。 當您的子類重新定義父類的方法並且仍想調用父類的實現時,您需要super()
,即:
class Example():
def __init__(self, text):
self.text = text
def printThis(self):
print(self.text)
class Child(Example):
def printThis(self):
print("this is a test")
super().printThis()
print("test passed")
在y類的init中,您還必須初始化要從其繼承的父類。
class x:
def __init__(self, text):
self.text = text
class y(x):
def __init__ (self, #other vars here ):
x.__init__(self, text)
self.othervars = othervars
def test():
self.printThis(self.text)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.