By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,199 Members | 1,125 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,199 IT Pros & Developers. It's quick & easy.

Adding functions to classes after definition

P: n/a
Consider: A)
>>class C(object):
.... pass
....
>>def f(*args):
.... print args
....
>>C.f = f
C.f
<unbound method C.f>
>>c=C()
c.f()
(<__main__.C object at 0x04A51170>,)

And B)
>>del c
C.f = types.MethodType(f, None, C)
C.f
<unbound method C.f>
>>c = C()
c.f()
(<__main__.C object at 0x04A51290>,)

I don't understand A). It is my vague understanding, that methods are
really properties that handle binding on attribute access, so B) should
be the "right" way to add a method to a class after definition. Why does
A show up as a method? Shouldn't it still just be a function? Certainly
when you define a class, there is some magic in the __new__ method that
turns functions in the initial dictionary into methods, but does this still
happen for all setattr after that? Is is possible to set a class attribute
equal to a regular (types.FunctionType) function?

Any references that discuss these issues would be greatly appreciated.

Thanks,
Gerard
Jan 9 '07 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.