I have a class that defines a set of callback functions (shown here as cb1well cb2). I save the map that I want to call after some event.
class Foo:
cb1 = None
cb2 = None
def test(self, input):
for (name, callback) in map:
if name == input:
if callback: callback()
...
map = {'one':cb1, 'two':cb2}
def mycallback():
print "mycallback()"
f = Foo()
f.cb1 = mycallback
f.test('one')
Can you spot the problem?
What happens when a class is initialized, the values cb1and cb2(which both None) are copied to the map. Therefore, even after the user "registers" the callback (by assigning cb1), the value on the card is still Noneand nothing is called.
Since in Python there is no such thing as “by reference,” how do I fix this?
source
share