Python callback functions and static methods

Chris Rebert clp at rebertia.com
Mon Jan 5 12:33:23 EST 2009


On Mon, Jan 5, 2009 at 9:00 AM, Joris <djm300 at gmail.com> wrote:
> Hello,
>
> I'm trying to implement callback functionality in a static class.
>
> I have a feeling that I'm doing something against the Python philosophy and
> not some programming error but any help would be appreciated.
>
> First, a piece of proof-of-concept-code:
>
> class Data:
>

The call to setCallBack effectively makes it as though you'd done this
(note that we're within the class body):

    def callfunc(a):
         print 'I received some data: '+ a

Obviously this method is not "static" in the Java sense, hence the
error about not being called with an instance. Here are my suggested
changes:

>
     @classmethod #class methods are closer to Java "static" methods;
Python static methods are just functions in a class
     def setCallBack(cls, callfunc):
         cls.callfunc = staticmethod(callfunc)
>
     @classmethod
     def OnData(cls, data):
         cls.callfunc(data)
>
>
> def DataCallback(a):
>     print 'I received some data: '+ a
>
> Data.setCallBack(DataCallback)
> Data.OnData('I have new data')
>
>

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list