How can I go about installing as a class variable a table that contains the entry points to the methods?
For clarification, consider the following -working- code:
class A(object):
def go(self, n):
method = self.table[n]
method(self)
def add(self):
print "add"
def multiply(self):
print "multiply"
table = {
1: add,
2: multiply,
}
>>> q = A()
>>> q.go(1)
add
However, I don’t like it much. I would like to have the table at the beginning for readability (the real world project is much bigger) and I don’t like the call using method(self). I think it’s very confusing.
My question is: Is there a better way or is the above code spot-on?
Thank you.
It already contains one. It’s called
__dict__.If you reaaaally want numeric indices, you can do e.g.
But that’s just silly, especially that strings are interned and using magic integers in place of them doesn’t buy you much, except for obscurity.