how to call back a method ?

Chris Angelico rosuav at gmail.com
Sun Aug 3 22:42:12 EDT 2014


On Mon, Aug 4, 2014 at 12:33 PM, elearn <elearn2014 at gmail.com> wrote:
> I want to call back a function which is the method of a class .
>
>     def callback(self.do,x):
>         return(self.do(x))
>
> That is what i want to write,when i input
>
>     def callback(self.do,x):
>
> error message:
>
>
>       File "<stdin>", line 1
>         def callback(self.do,x):
>                      ^
>     SyntaxError: invalid syntax
>
>
> `do` is a method in my class ,how to write the code?

You don't want to define it with the dot in there. Give it a name like
'func' (or preferably, something more descriptive):

    def callback(func,x):
        return func(x)

(And I took the superfluous parentheses off 'return'; it's a
statement, not a function.)

If self is an object, then self.do is an attribute of that object,
which in your case is a callable function. You can assign that to
anything, pass it around, and so on, and you don't need "self.do" as
the name. Try it like this, see if it works... but have a careful look
at your design, too. You may well be overthinking this.

ChrisA



More information about the Python-list mailing list