Issue
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.
Solution
It already contains one. It's called __dict__
.
class foo(object):
def go(self, method):
getattr(self, method)()
def a(self):
...
def b(self):
...
If you reaaaally want numeric indices, you can do e.g.
class foo(object):
methods = { 1: 'a', 2: 'b' }
def go(self, n):
getattr(self, self.methods[n])()
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.
Answered By - Cat Plus Plus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.