Peter Otten wrote:
You are right; the misunderstanding is that I wasn't advertising the above
"fancy" solution (which is buggy, btw).
Yes, I wasn't sure about the irony in you last post ;)
Peter Otten wrote:
I have now implemented what I had in mind with the protocol to function name
mapping, and I think /that/ is reasonably complex. I'm using instance
methods in the demo, but it should work with class methods as well.
class Error(Exception):
def __init__(self, protocol):
Exception.__init__(self, self.template.format(protocol))
class UnknownProtocolError(Error):
template = "Unknown protocol {}"
class ProtocolNotSupportedError(Error):
template = "Protocol {} not supported"
FOO = (42, 17)
BAR = (1, 2)
BAZ = (3, 4)
HAM = (4, 5)
SPAM = (5, 6)
class HandlersBase(object):
protocol_to_methodname = {
FOO: "foo",
BAR: "bar",
BAZ: "baz",
HAM: "ham",
}
def get_handler(self, protocol):
try:
methodname = self.protocol_to_methodname[protocol]
except KeyError:
raise UnknownProtocolError(protocol)
method = getattr(self, methodname, None)
if method is None:
raise ProtocolNotSupportedError(protocol)
return method
class A(HandlersBase):
def foo(self): print "A.foo"
def bar(self): print "A.bar"
def baz(self): print "A.baz"
class B(A):
def bar(self): print "B.bar"
baz = None # hide parent implementation
if __name__ == "__main__":
for Class in A, B:
inst = Class()
print "---", Class.__name__, "---"
for protocol in FOO, BAR, BAZ, SPAM:
try:
inst.get_handler(protocol)()
except Error as err:
print err
Thanks for the code! It's very similar to what I implemented but more
flexible regarding inheritance.
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor