1

I have a class similar to the below, which works well for my simple usage.

However calling the functions in this way means they don't have access to self. so I can't use any of the other member functions or variables. Note that some items share the same callback.

Is there a better way to reference or call the functions so that I have access to other items relating to self?

class Foo:
    def dostuff(self, bar):
        # ...
        # Do stuff with input data, occasionally invoking the right callback
        # function like so:
        self.options[i]['func'](mydata)

    def callback1(data):
        pass

    def callback2(data):
        pass

    options = [
        0x10: { 'name': 'cat', 'func': callback1 },
        0x20: { 'name': 'dog', 'func': callback2 },
        0x40: { 'name': 'emu', 'func': callback2 },
        0x80: { 'name': 'bat', 'func': callback2 }
    ]

2 Answers 2

1

Since you don't have access to self, you will need to defer looking up the method. You can look it up by name inside dostuff:

class Foo:
    def dostuff(self, bar):
        # ...
        # Do stuff with input data, occasionally invoking the right callback
        # function like so:
        method = getattr(self, self.options[i]['func'])
        method(mydata)

    def callback1(self, data):
        pass

    def callback2(self, data):
        pass

    options = [
        0x10: { 'name': 'cat', 'func': 'callback1' },
        0x20: { 'name': 'dog', 'func': 'callback2' },
        0x40: { 'name': 'emu', 'func': 'callback2' },
        0x80: { 'name': 'bat', 'func': 'callback2' }
    ]
Sign up to request clarification or add additional context in comments.

2 Comments

Don't forget to add self arguments to the callbacks.
Thanks for this, makes total sense.
1

Your member functions need to include a "self" parameter even if they are intended only for self dispatched calls.

In other words you need something like:

#!/bin/python
# ...
class ...
   def callback(self, data):
       # ...

... and it needs to be called with self.callback(some_data)

Also note that you've defined Too.options as class data rather than a member attribute. It's accessible without any instantiation, but you should keep your intentions clear to those reading your code by consistent referring to these as Foo.options and never as some_instance.options (the latter would work, but obscures the nature of .options by being easily mistaken for an instance member (attribute).

1 Comment

Thank you for the second point, which I now understand. However the thung I was missing was explained by Ned, specifically he deferred lookup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.