I currently have a system of classes that register callbacks and then call them when certain conditions are met. However I am running into some problems storing the function object.
A:
class Foo(object):
_callback = None
@classmethod
def Register(cls, fn):
cls._callback = fn
def Bar():
print "Called"
Foo.Register(Bar)
Foo._callback()
input clear Python 2.7.10 (default, Jul 14 2015, 19:46:27) [GCC 4.8.2] on linux
Traceback (most recent call last): File "python", line 12, in <module>
TypeError: unbound method Bar() must be called with Foo instance as first argument (got nothing instead)
I am not sure why it requires a Foo instance when the function is not a member of Foo.
B:
class Foo(object):
_callback = []
@classmethod
def Register(cls, fn):
cls._callback.append(fn)
def Bar():
print "Called"
Foo.Register(Bar)
Foo._callback[0]()
Why does the first version not work while the second version does? What functionality differs when adding it to a list instead.
Foowhen you docls._callback = fn