What does it mean by the 'super object returne

2019-03-26 00:53发布

问题:

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

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

Which is super(type).

I am wondering what is unbounded and when is it bounded.

回答1:

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]: <unbound method Foo.bar>

In [3]: a = Foo()

In [4]: a.bar
Out[4]: <bound method Foo.bar of <__main__.Foo object at 0x4433110>>

In [5]: a.bar()
<__main__.Foo object at 0x4433110>

In [6]: Foo.bar()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-bb3335dac614> in <module>()
----> 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>


回答2:

"Unbound" means it will return the class, rather than an instance of the class.