这里的super调用了什么?

作者站长头像
站长
· 阅读数 16

super用来调用父类方法。

class Student:
    def __init__(self, name, math, chinese):
        self.name = name
        self.math = math
        self.chinese = chinese
    def __getattribute__(self, item):
        print("调用 __getattribute__")
        return super(Student, self).__getattribute__(item)

super指向父类,这里Student的父类object,如何理解super(Student, self).__getattribute__(item)?调用object里面的__getattribute__,这个也不好理解?

我感觉这里的super(Student, self)没有指向它的父类,指向了它自身?

回复
1个回答
avatar
test
2024-07-13

https://docs.python.org/zh-cn...

这是官方文档, 注意里面的属性 __mro__, 你再看一下你这个类的 Student.__mro__ 就明白了.

文档上说

For example, if __mro__ of object_or_type is D -> B -> C -> A -> object and the value of type is B, then super() searches C -> A -> object.

在你的示例中, Student.__mro__ 的值是 (Student, object) , 所以搜索的就是 object

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容