Tobias M. wrote:
> Peter Otten wrote:
>> Build the list outside the class: MyClass.method_list = [MyClass.bar]
> Thanks, that is a solution. But I don't really like to put the list
> outside the class as it is strongly related to the class and not used
> outside.
> Actually in my code it's not a list but a dictionary. The class is part
Well, I usually prefer to keep things simple, but you can do the binding
manually:
>>> class A(object):
... @classmethod
... def foo(cls):
... print "Hello from A.foo()"
... lookup = {"foo": foo}
... @classmethod
... def get_handler(cls, packet_type):
... return cls.lookup[packet_type].__get__(None, cls)
...
>>> A.get_handler("foo")()
Hello from A.foo()
If you adopt this approach you might omit the lookup dictionary and use
getattr():
>>> class B(object):
... @classmethod
... def handle_foo(cls): print "Hello from B.handle_foo()"
... @classmethod
... def get_handler(cls, packet_type):
... return getattr(cls, "handle_" + packet_type)
...
>>> B.get_handler("foo")()
Hello from B.handle_foo()
(I've added the "handle_" prefix so an attacker can't just invent package
types to have arbitrary methods invoked.)
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor