Storing a callback function as a class member

Ian Kelly ian.g.kelly at gmail.com
Wed Jul 7 20:35:25 EDT 2010


On Wed, Jul 7, 2010 at 3:48 PM, 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?

No, self will not be passed as a parameter.  A function is only
treated as a method when it is present in the class dict.  If it is in
the instance dict as you have above, then it's just a normal function.
 If you want it to receive self in this case, then you should have
your callCallback method pass it in explicitly.

HTH,
Ian



More information about the Python-list mailing list