implementing callback function

7stud bbxx789_05ss at yahoo.com
Fri Jun 1 07:47:39 CEST 2007


Ron Provost wrote:
> class X( object ):
>    fn = None

>    @staticmethod
>    def callX( n ):
>       return X.fn( n )

> Now, the following global stuff represents my higher-level routines:

> def fn_impl( n ):   # my callback
>    return n + 1

> X.fn = fn_impl      # register my callback

> Now I can do something which forces my callback (fn_impl) to get called

> print X.callX( 3 )

> I think I would get '4' printed but instead get the above error.  What
> am I doing wrong?


callX is a static method, so it does not require an instance as the
first argument.  However, that's not true for fn_impl.

This line of code:

> X.fn = fn_impl

makes fn_impl an attribute of the class.  If you call a function that
is a class attribute, python creates a method out of the function. A
method requires that the first argument be an instance.  If you call
the method through an instance, python automatically sends the
instance as the first argument to the method.  If you call the method
using the class, then you have to supply the instance argument
yourself.

In this line:

return X.fn( n )

You are calling a function that is a class attribute and you are
calling it through the class, so you have to supply an instance as the
first argument yourself.




More information about the Python-list mailing list