'class' argument optional for new.instancemethod?

Peter Hansen peter at engcorp.com
Sat Mar 12 02:31:31 CET 2005


Martin Miller wrote:
> In section "3.27 new -- Creation of runtime internal objects" of the
> documentation that comes with Python 2.4 it says:
> 
>>instancemethod(function, instance, class)
[...]
> However, some simple experiments I've tried seem to indicate that the
> last argument, 'class' can be left off with no ill effects, and is
> therefore optional.
> 
> Doesn't anyone know if this is a documention problem? Personally, I
> don't understand how the argument gets used when it *is* provided -- if
> nothing else, having it seems somewhat redundant given the presence of
> the 'instance' argument.

A little experimentation reveals at least one thing that
argument affects:

 >>> import new
 >>> class A:
...  pass
...
 >>> class B:
...  pass
...
 >>> def f(self):
...  print 'in f', self
...
 >>> a = A()
 >>> a.f = new.instancemethod(f, a)
 >>> a.f()
in f <__main__.A instance at 0x00AE5EB8>
 >>> a.g = new.instancemethod(f, a, B)
 >>> a.g()
in f <__main__.A instance at 0x00AE5EB8>
 >>> a.g
<bound method B.f of <__main__.A instance at 0x00AE5EB8>>
 >>> a.f
<bound method ?.f of <__main__.A instance at 0x00AE5EB8>>

So without the class argument, at least in this small
sample, the bound method doesn't know what class
it belongs to, at least for purposes of printing
it's own repr().

-Peter



More information about the Python-list mailing list