[Tutor] Problem with calling class methods stored in a list
Peter Otten
__peter__ at web.de
Thu Jan 10 15:15:35 CET 2013
Tobias M. wrote:
> Am 10.01.2013 13:48, schrieb Peter Otten:
>> If you adopt this approach you might omit the lookup dictionary and use
>> getattr():
>>
>> ... @classmethod
>> ... def handle_foo(cls): print "Hello from B.handle_foo()"
>> ... @classmethod
>> ... def get_handler(cls, packet_type):
>> ... return getattr(cls, "handle_" + packet_type)
>> ...
> Well I think this is an elegant solution.
>
> But due to my protocol a packet type is uniquely defined by a
> combination of two header fields (that contain integers). Building a
> verbose method name from these would complicate it again.
Technically, not much:
>>> class C(object):
... @classmethod
... def handle_1_42(self): print "Hi"
... @classmethod
... def get_handler(cls, packet_type):
... return getattr(cls, "handle_%d_%d" % packet_type)
...
>>> C.get_handler((1, 42))()
Hi
Of course handle_1_42() is not exactly the method name one would hope for.
You could, again, strive for simplicity and add a lookup table that maps
protocol tuples to function /names/ , but as simplicity doesn't seem to be
your cup of tea:
class HandlersType(type):
def __init__(cls, name, bases, classdict):
cls.lookup_protocol = lookup = {}
for k, v in classdict.items():
if isinstance(v, protocol_method):
lookup[v.protocol] = getattr(cls, k)
class protocol_method(classmethod):
pass
def protocol(x, y):
def attach_protocol(f):
f = protocol_method(f)
f.protocol = x, y
return f
return attach_protocol
class D:
__metaclass__ = HandlersType
@protocol(42, 17)
def foo(cls):
print "Hi"
D.lookup_protocol[42, 17]()
;)
More information about the Tutor
mailing list