【发布时间】:2013-11-19 06:21:00
【问题描述】:
当我们实例化一个类时,方法会为每个创建的实例“绑定”到该特定实例。 “绑定”这个词在这里是什么意思。我认为不会为每个实例创建方法对象的重复副本
我已经阅读了与类的每个实例的方法“绑定”相关的开销。这是什么开销
【问题讨论】:
标签: python python-2.7 python-3.x
当我们实例化一个类时,方法会为每个创建的实例“绑定”到该特定实例。 “绑定”这个词在这里是什么意思。我认为不会为每个实例创建方法对象的重复副本
我已经阅读了与类的每个实例的方法“绑定”相关的开销。这是什么开销
【问题讨论】:
标签: python python-2.7 python-3.x
这意味着它绑定到一个实例。 IE。该实例作为self 参数传递
class Foo(object):
def bar(self):
print "The instance is:", self
foo = Foo()
以下效果相同
foo.bar() # call bound method. instance gets passed in automatically
Foo.bar(foo) # unbound method. first parameter should be an instance
【讨论】:
简单地说,一个未绑定的方法需要你为self传递一个对象。
绑定方法会自动将类实例作为self 传递。
另请参阅 this answer 并查看 at descriptors 以更好地了解方法。
在代码中:
# class definition
>>> class Foo:
>>> def bar(self):
>>> print 'self:', self
# class instance -> bound method
>>> a = Foo()
>>> print a, a.bar
<__main__.Foo instance at 0x107bcda70> <bound method Foo.bar of <__main__.Foo instance at 0x107bcda70>>
>>> a.bar()
self: <__main__.Foo instance at 0x107bcda70>
# class -> unbound method
>>> print Foo, Foo.bar
__main__.Foo <unbound method Foo.bar>
>>> Foo.bar()
TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead)
# manually binding a method
>>> b = Foo.bar.__get__(a, Foo)
>>> print b
<bound method Foo.bar of <__main__.Foo instance at 0x107bcda70>>
>>> b()
self: <__main__.Foo instance at 0x107bcda70>
【讨论】: