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

标签 python

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

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/

相关文章:

python - 多个列表中每个元素的平均值 - Python

python - 在Python中同时检查列表中的所有项目

python - pygame加载更改文件名的图像

python - 寻找一种按休息时间分割类次的算法

python - 如何从 lxml 获取原始 XML?

python - 如何避免 os.system() 在 python 中打印出返回值

python - 在 AWS Elastic Beanstalk 上部署 python Web 服务器

python - 从 pandas 的已知索引中获取行数据

python - 如何使用 Pandas 删除数字中 2 个小数点中的 1 个

python - 使用 bot Telegram API 转发包含多个媒体文件的消息