Dynamic class methods misunderstanding

Bill Mill bill.mill at gmail.com
Fri Jan 28 11:25:50 EST 2005


Hans,


On Fri, 28 Jan 2005 11:09:16 -0500, Hans Nowak <hans at zephyrfalcon.org> wrote:
<snip>
> 
> m is a function.  When you assign it to self.method, it's still a
> function.  You don't create a new method that way; all you have is a new
> attribute called 'method' containing the function.
> 

I figured as much; I just didn't know how to add it as a method.

> To add m as a new method to the *class*, do this:
> 
>  >>> class test:
> ...     def __init__(self, method):
> ...         self.__class__.method = method
> ...         self.method()
> ...
>  >>> def m(self): print self
> ...
>  >>> test(m)
> <__main__.test instance at 0x0192ED78>
> <__main__.test instance at 0x0192ED78>

When I run it, I only get one call to m, which is how I would expect
python to work; I assume the double printing here is a typo?

>  >>>
> 
> To add m as a new method to the *instance*, use new.instancemethod, as
> Diez B. Roggisch already pointed out.
> 

Thanks, you helped me understand it a lot.

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list