推荐学习书目
› 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 · Aug 30, 2017 · 2431 views
    This topic created in 3315 days ago, the information mentioned may be changed or developed.

    网上很多文档都说,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 replies  •  2017-08-30 15:10:32 +08:00
    eastpiger
        1
    eastpiger  
       Aug 30, 2017
    ```
    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1249 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 16:55 · PVG 00:55 · LAX 09:55 · JFK 12:55
    ♥ Do have faith in what you're doing.