【发布时间】:2016-03-31 09:04:50
【问题描述】:
假设一个Python类有不同的方法,根据用户指定的不同,在主函数calculate()中执行不同的方法。
在下面的示例中,用户需要指定关键字参数'methodOne' 或'methodTwo'。如果没有指定或指定了不正确的关键字,则默认为'methodOne'。
class someClass(object):
def __init__(self,method=None):
methodList = ['methodOne','methodTwo']
if method in methodList:
self.chosenMethod = method
else:
self.chosenMethod = self.methodOne
def methodOne(self):
return 1
def methodTwo(self):
return 2
def calculate(self):
return self.chosenMethod()
上面显然不起作用,因为method 是一个字符串而不是一个函数。如何根据我的关键字参数method 选择self.methedOne() 或self.methedOne()?原则上,以下工作:
def __init__(self,method=None):
if method == 'methodOne':
self.chosenMethod = self.methodOne
elif method == 'methodTwo':
self.chosenMethod = self.methodTwo
else:
self.chosenMethod = self.methodOne
但如果我有两个以上的方法,这会变得相当难看。有没有办法做到这一点类似于我的原始代码?
【问题讨论】:
-
下面的答案已经显示了
getattr的使用。这种方法称为反射(或自省):检查自身结构的代码。但是,请记住,如果method是用户提供的值,您最好验证它是否引用了预期的方法之一。毕竟,用户可以输入'calculate',或'__class__',或不可调用属性的名称,从而导致各种问题(甚至可能是安全风险,具体取决于上下文)。 -
@PieterWitvoet
if method in methodList子句应该防止这种情况发生。 -
@Forzaa:很好。 :)
标签: python class methods keyword