如何将包含方法入口点的表作为类变量安装?
为了澄清,请考虑以下工作代码:
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
但是,我不喜欢它。我想在开头提供表格以便于阅读(真实世界的项目要大得多),我不喜欢使用method(self)
的呼叫。我认为这很令人困惑。
我的问题是:是否有更好的方法或上述代码是否正确?
谢谢。
答案 0 :(得分:6)
它已包含一个。它被称为__dict__
。
class foo(object):
def go(self, method):
getattr(self, method)()
def a(self):
...
def b(self):
...
如果你真的想要数字索引,你可以这样做。
class foo(object):
methods = { 1: 'a', 2: 'b' }
def go(self, n):
getattr(self, self.methods[n])()
但这很愚蠢,特别是字符串被实习并使用魔术整数取代它们并不会给你带来太大的影响,除了默默无闻。
答案 1 :(得分:1)
我不确定我为什么要这样做,但你可以这样解决它:
class A(object):
table = {
1: "add",
2: "multiply",
}
def go(self, n):
method = getattr(self, self.table[n])
method()
def add(self):
print "add"
def multiply(self):
print "multiply"
>>> a = A()
>>> a.go(1)
add
阅读您对Cat Plus Plus的回复后进行编辑:
如果您只想在现有方法中使用别名,那么可以采用更简单的方法 - 也许您希望能够在威尔士语中调用这些方法:
class A(object):
table = {
1: "add",
2: "multiply",
}
def go(self, n):
method = getattr(self, self.table[n])
method()
def add(self):
print "add"
def multiply(self):
print "multiply"
ychwanegu = add
lluosi = multiply
>>> a = A()
>>> a.lluosi()
multiply