Bill Mill wrote:
Hello all,

I have a misunderstanding about dynamic class methods. I don't expect
this behavior:

In [2]: class test:
   ...:      def __init__(self, method):
   ...:         self.method = method
   ...:         self.method()
   ...:

In [3]: def m(self): print self
   ...:
[...]

TypeError: m() takes exactly 1 argument (0 given) -----------------------------------------------------------------------------

Why doesn't m get the implicit self parameter in the self.method()
call? How would I make it a proper member of the class, so that a
self.method() call would work with the above "m" function?

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.


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>
>>>

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

HTH,

--
Hans Nowak
http://zephyrfalcon.org/

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to