Python 关于 super 的疑问

2017-08-30 15:00:38 +08:00
 yujianwjj

网上很多文档都说,super()返回的是 MRO 中的下一个类。

class Animal(object):
    def __init__(self, name):
        self.name = name

    def greet(self):
        print('Hello, I am {}'.format(self.name))


class Dog(Animal):
    def greet(self):
        super().greet()
        print('WangWang...')

dog = Dog('dog')
dog.greet()

按照网上的教程理解,super()返回的是 mro 中的下一个类,那么 super()返回的应该是 Animal,那么如果是 Animal 的话,super().greet(),就应该相当于Animal.greet(),但是这样的话肯定是不能调用的,应该是Animal.greet(self),才好理解。

而且通过 print(super()) 得到的返回值是 <super: <class 'Dog'>, <Dog object>>,说明 super 是一个类。

那么,super() 返回的到底是什么?

1658 次点击
所在节点    Python
1 条回复
eastpiger
2017-08-30 15:10:32 +08:00
```
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.
```

https://docs.python.org/3/library/functions.html?highlight=super#super

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/386885

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX