Storing a callback function as a class member

Rhodri James rhodri at wildebst.demon.co.uk
Wed Jul 7 18:23:24 EDT 2010


On Wed, 07 Jul 2010 22:48:11 +0100, Nathan Huesken  
<python at lonely-star.org> wrote:

> Hi,
>
> I have a class, where I want to store a callback function as a member
> to access later:
>
> class CallbackClass:
>     def setCallback(self,cb):
>         self.cb = cb
>
>     def callCallback(self, para):
>         self.cb(para)
>
> Doing so, I get the error:
> callbackFunc() takes exactly 1 parameter (2 given)
>
> self is given as parameter this way, is it not? How can this be done?

rhodri at gnudebst:~$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class CBClass:
...     def set_cb(self, cb):
...             self.cb = cb
...     def call_cb(self, para):
...             self.cb(para)
...
>>> def trivial(arg):
...     print arg
...
>>> c = CBClass()
>>> c.set_cb(trivial)
>>> c.call_cb("Hello, world")
Hello, world

Works for me.  Which version of Python are you using?

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list