apply for objects

Donn Cave donn at u.washington.edu
Thu Jun 22 12:09:53 EDT 2000


Quoth Sander Hahn <shahn at cs.vu.nl>:
| I wanted to call a method of an object in Python.
...
| That works, however when you use apply on a method you get the following
| error:
|
| >>> class C:
| 	def m(x, y):
| 		print str(x) + str(y)
|
|
| >>> c = C()
|
| >>> apply(c.m, ('hello', ' bye now'), {})
| Traceback (innermost last):
|   File "<pyshell#12>", line 1, in ?
|     apply(c.m, ('hello', ' bye now'), {})
| TypeError: too many arguments; expected 2, got 3
|
| I previously got errors about no __call__ or something weird...!?!
| However i found out that you must use the im_func from the method to get
| the corresponding function:
|
| >>> apply(c.m.im_func, ('hello', ' bye now'), {})
| hello bye now
|
| So, my problem is solved for now :-)

No, it isn't!  Your problem is just that you defined your class
method without its 1st class instance parameter.

    class C:
        def m(self, x, y):
            print str(x) + str(y)

That's the third argument you didn't expect.  Define it this way
and it will work fine without any im_func hackery.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list