V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
yujianwjj
V2EX  ›  Python

Python 关于 super 的疑问

  •  
  •   yujianwjj · 2017-08-30 15:00:38 +08:00 · 1650 次点击
    这是一个创建于 2431 天前的主题,其中的信息可能已经有所发展或是发生改变。

    网上很多文档都说,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() 返回的到底是什么?

    1 条回复    2017-08-30 15:10:32 +08:00
    eastpiger
        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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5367 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 08:38 · PVG 16:38 · LAX 01:38 · JFK 04:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.