difference between class methods and instance methods

Duncan Booth duncan.booth at invalid.invalid
Thu Feb 17 12:11:33 EST 2005


Diez B. Roggisch wrote:

> John wrote:
>> ... hmm... bound methods get created each time you make
>> a call to an instance method via an instance of the given class?
> 
> No, they get created when you create an actual instance of an object.
> So only at construction time. Creating them means taking the unbound
> method and binding the created object as first argument to the method.
> Thus each instance of a class Foo with a method bar has its own
> instance of bar - the bound method bar. But only one per object. 
> 
> 
This is badly wrong. John was correct.

Bound methods get created whenever you reference a method of an instance. 
If you are calling the method then the bound method is destroyed as soon as 
the call returns. You can have as many different bound methods created from 
the same unbound method and the same instance as you want:

>>> inst = C()
>>> f1 = inst.foo
>>> f2 = inst.foo
>>> f1, f2
(<bound method C.foo of <__main__.C instance at 0x00B03F58>>, <bound method 
C.foo of <__main__.C instance at 0x00B03F58>>)
>>> f1 is f2
False
>>> f1 is inst.foo
False
>>> 

Every reference to inst.foo is a new bound method.



More information about the Python-list mailing list