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

时光总嘲笑我的痴心妄想 提交于 2019-12-21 04:11:06

问题


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.



来源:https://stackoverflow.com/questions/22403897/what-does-it-mean-by-the-super-object-returned-is-unbound-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!