調用超級當我試圖理解下面的代碼。瞭解自己是什麼樣的孩子
class Base(object):
def __init__(self):
print(self.__class__.__name__)
def handle(self):
print("Beginning handle Base")
self.template()
def template(self):
print("template of Base")
class Child(Base):
def __init__(self):
super(Child, self).__init__()
def handle(self):
print("Beginning handle Child")
super(Child, self).handle()
def template(self):
print("template of Child")
parent = Base()
child = Child()
在這裏我希望下面的打印
'Base'
'Child'
所以這是好的,只是當我把這:
parent.handle()
child.handle()
我希望:
"Beginning handle Base"
"template of Base"
"Beginning handle Child"
"Beginning handle Base"
"template of Base"
但是我得到
"Beginning handle Base"
"template of Base"
"Beginning handle Child"
"Beginning handle Base"
"template of Child"
這究竟是爲什麼?在base的句柄函數中不是self.template()引用base的模板函數? super(Child, self).handle()
究竟在做什麼?對我來說,似乎它調用了手柄的它的父,但設置自我本身......
'Child'''''中的ChildB'是什麼? – ShadowRanger
這應該是'孩子'......已更新問題 – barrigaj
當調用'child.handle()'時,'self'始終是'child'。它被傳遞給'Base.handle',但它仍然是'child',所以當'Base.handle'調用'self.template()'時,它會調用'Child.template'。 –