简体   繁体   English

“绑定”一词在类方法中意味着什么

[英]what does the term 'bound' means in class method

When we instantiate a class, the methods get 'bound' to that particular instance for every instance created. 当我们实例化一个类时,方法将为每个创建的实例“绑定”到该特定实例。 What does the word 'bound' means here. “绑定”一词在这里是什么意思。 I don't think a duplicate copy of the method object is created for every instance 我不认为每个实例都会创建方法对象的副本

I have read there is overhead associated with 'binding' the methods for every instance of the class. 我已经读过,对于类的每个实例,与“绑定”方法有关的开销很大。 What kind of overhead is this 这是什么样的开销

It means it is bound to an instance. 这意味着它已绑定到实例。 ie. 即。 That instance gets passed as the self parameter 该实例作为self参数传递

class Foo(object):
    def bar(self):
        print "The instance is:", self

foo = Foo()

The following have the same effect 以下有相同的效果

foo.bar()        # call bound method. instance gets passed in automatically
Foo.bar(foo)     # unbound method. first parameter should be an instance

Simply, an unbound method requires you to pass an object in for self . 简单来说,无界方法要求您为self传递一个对象。

A bound method automatically passes the class instance as self . 绑定方法自动将类实例作为self传递。

Also see this answer and take a look at descriptors for a better understanding of methods. 另请参见此答案并查看描述符 ,以更好地理解方法。

In code: 在代码中:

# 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM