What does it mean by the 'super object returned is unbound' in python?

前端 未结 4 1305
轻奢々
轻奢々 2021-02-05 21:34

According to http://docs.python.org/2/library/functions.html#super,

If the second argument is omitted, the super object returned is unbound.

4条回答
  •  囚心锁ツ
    2021-02-05 21:35

    Edit: in the context of super, much of below is wrong. See the comment by John Y.

    super(Foo, a).bar returns the method called bar from the next object in the method resolution order (the MRO), in this case bound to the object a, an instance of Foo. If a was left out, then the returned method would be unbound. Methods are just objects, but they can be bound or unbound.

    An unbound method is a method that is not tied to an instance of a class. It doesn't receive the instance of the class as the implicit first argument.

    You can still call unbound methods, but you need to pass an instance of the class explicitly as the first argument.

    The following gives an example of a bound and an unbound method and how to use them.

    In [1]: class Foo(object):
       ...:     def bar(self):
       ...:         print self
       ...:         
    
    In [2]: Foo.bar
    Out[2]: 
    
    In [3]: a = Foo()
    
    In [4]: a.bar
    Out[4]: >
    
    In [5]: a.bar()
    <__main__.Foo object at 0x4433110>
    
    In [6]: Foo.bar()
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
     in ()
    ----> 1 Foo.bar()
    
    TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead)
    
    In [7]: Foo.bar(a)
    <__main__.Foo object at 0x4433110>
    

提交回复
热议问题