instances from bound methods

Nick Craig-Wood nick at craig-wood.com
Thu Mar 2 13:30:13 EST 2006


I needed to find the instance from a bound method.  Eg

  >>> class C(object):
  ...     def fn(self): print "hello"
  ... 
  >>> c=C()
  >>> fn=c.fn
  >>> fn
  <bound method C.fn of <__main__.C object at 0xb7dd2acc>>
  >>> fn.im_self
  <__main__.C object at 0xb7dd2acc>
  >>> fn.__self__
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  AttributeError: 'function' object has no attribute '__self__'
  >>>

But I discovered that builtin objects work in a completely different
way

  >>> fd=open("myfile","w")
  >>> fn=fd.write
  >>> fn.im_self
  Traceback (most recent call last):
    File "<stdin>", line 1, in ?
  AttributeError: 'builtin_function_or_method' object has no attribute 'im_self'
  >>> fn.__self__
  <open file 'myfile', mode 'w' at 0xb7dc1260>
  >>> 

I wonder why?

Is there a canonical way of doing it?

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list