Dynamically adding and removing methods
Steven Bethard
steven.bethard at gmail.com
Wed Sep 28 19:20:04 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.
> If you lookup in class.__dict__, the function is still a function.
>
>
>>>>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>>
>
> I am not sure, without looking, how much of this is language definition and
> how much CPython implementation, but I think mostly the latter
Well, being that the descriptor machinery is defined in the language
reference[1][2], I'd have to say it's entirely the former. The
descriptor machinery says basically that, for classes,
C.meth
should always be doing the equivalent of:
C.__dict__['meth'].__get__(None, C)
and for instances,
c.meth
should always be doing the equivalent of:
type(c).__dict__['meth'].__get__(c, type(c))
[1] http://docs.python.org/ref/descriptors.html
[2] http://docs.python.org/ref/descriptor-invocation.html
STeVe
More information about the Python-list
mailing list