[Tutor] Problem with calling class methods stored in a list

eryksun eryksun at gmail.com
Thu Jan 10 14:10:40 CET 2013


On Thu, Jan 10, 2013 at 7:48 AM, Peter Otten <__peter__ at web.de> wrote:
>
> 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.)

This approach also makes it simpler to override handlers in a
subclass. You don't have to worry about separately updating a copy of
a list or dict.


More information about the Tutor mailing list