You need to make some changes to changes to eventToMethod
first, don't assign do1
, do2
to it, better assign strings. You can always access class attributes using strings. The problem with storing references to do1
and do2
in dictionary is that they are not bound methods yet(they're simply classmethod
objects(non-data descriptors)) when you store them in dictionary, it's only after the completion of class definition that they're converted to fully bound class methods.
eventToMethod = {'1': 'do1',
'2': 'do2'}
And then use getaattr
to get the method:
@classmethod
def onEvent(cls, name):
method = getattr(cls, cls.eventToMethod.get(name))
...
Note that you can also directly pass 'do1'
to onEvent
instead of keeping a dictionary to store names and then simply use:
method = getattr(cls, name)
You can still get away with your current approach if you call __get__
method of do1
, do2
descriptors explicitly.:
method = cls.eventToMethod.get(name)
if method != None:
method.__get__(None, cls)()
This works because this is exactly what Python does under the hood, classmethod
is a non-data descriptor
and when you do Thing.do1
Python actually calls __get__
method of do1
with first agument as None and second as type:
>>> Thing.do1.__get__(None, Thing)
<bound method type.do1 of <class '__main__.Thing'>>
>>> Thing.do1.__get__(None, Thing)
<bound method type.do1 of <class '__main__.Thing'>>
>>> Thing.do1
<bound method type.do1 of <class '__main__.Thing'>>
>>> Thing.eventToMethod['1'].__get__(None, Thing) #Using OP's code.
<bound method type.do1 of <class '__main__.Thing'>>