2

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

user634615
  • 647
  • 7
  • 17

2 Answers2

0

It means it is bound to an instance. ie. That instance gets passed as the self parameter

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
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0

Simply, an unbound method requires you to pass an object in for self.

A bound method automatically passes the class instance as 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>
Community
  • 1
  • 1
lunixbochs
  • 21,757
  • 2
  • 39
  • 47