gpt4 book ai didi

python - 在对 child 调用 super 时理解什么是 self

转载 作者:太空宇宙 更新时间:2023-11-04 08:03:56 24 4
gpt4 key购买 nike

我正在尝试理解下面的代码。

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的handle函数中的self.template()不是指的是base的模板函数吗? super(Child, self).handle() 实际上在做什么?对我来说,它似乎是在调用其父级的句柄,但将自身设置为自身......

最佳答案

Python 2 Documentation :

super(type[, object-or-type])
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

所以在你的情况下 super(Child, self).handle() 做下一步:

调用 Child(即 Base)父级的 handle 方法并将 Child 实例作为 传递>self 到那个方法。

看看您的代码片段中发生了什么:

parent.handle()
// Calling handle of parent, nothing special.
// "Beginning handle Base"
// "template of Base"
child.handle()
// Calling handle of child: "Beginning handle of Child" - logged
// handle method of child calls handle method of parent: "Beginning handle Base" - logged
// handle method of Base calls template method of self which is template method of Child as self passed to super as second parameter.: "template of Child" - logged

所以这是上面代码片段的正常行为。

关于python - 在对 child 调用 super 时理解什么是 self ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35099099/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com