Dynamically adding and removing methods

Ron Adam rrr at ronadam.com
Thu Sep 29 15:02:29 EDT 2005


Terry Reedy wrote:

> "Ron Adam" <rrr at ronadam.com> wrote in message 
> news:sXA_e.112986$xl6.67455 at tornado.tampabay.rr.com...
> 
>>Actually I think I'm getting more confused.  At some point the function
>>is wrapped.  Is it when it's assigned, referenced, or called?
> 
> 
> When it is referenced via the class.

Ok, that's what I suspected.  Thanks for clarifying this.

>  If you lookup in class.__dict__, the function is still a function.

Now why did I not think of doing that?  :-)


>>>>class C(object):
> 
> ...   def meth(self): pass
> ...
> 
>>>>C.__dict__['meth']
> 
> <function meth at 0x0090B018>
> 
>>>>C.meth
> 
> <unbound method C.meth>
> 
>>>>C().meth
> 
> <bound method C.meth of <__main__.C object at 0x008E4688>>

Ok, I got it now.  Given class 'C' below, i.m(1)  does....

 >>> class C(object):
...    def m(self, x):
...       return repr(x)
...
 >>> i = C()
 >>> boundmeth = i.__getattribute__('m')
 >>> boundmeth
<bound method C.m of <__main__.C object at 0x009D1C70>>
 >>> boundmeth(1)
'1'

 >>> import dis
 >>> dis.dis(boundmeth)
   3           0 LOAD_GLOBAL              0 (repr)
               3 LOAD_FAST                1 (x)
               6 CALL_FUNCTION            1
               9 RETURN_VALUE
 >>> dis.dis(C.m)
   3           0 LOAD_GLOBAL              0 (repr)
               3 LOAD_FAST                1 (x)
               6 CALL_FUNCTION            1
               9 RETURN_VALUE
 >>> dis.dis(C.__dict__['m'])
   3           0 LOAD_GLOBAL              0 (repr)
               3 LOAD_FAST                1 (x)
               6 CALL_FUNCTION            1
               9 RETURN_VALUE

Hmm... that didn't tell me anything. (?)

 >>> boundmeth
<bound method C.m of <__main__.C object at 0x009D1C70>>
 >>> C.m
<unbound method C.m>
 >>> C.__dict__['m']
<function m at 0x009D6930>

Time to start digging around in the source code I guess.  ;-)

> I am not sure, without looking, how much of this is language definition and 
> how much CPython implementation, but I think mostly the latter, as long as 
> the inheritance tree lookup behavior is as specified.
> 
> Terry J. Reedy

Yes, it hard to tell sometimes where CPython ends and Python begins.

Cheers,
Ron




More information about the Python-list mailing list