假设一个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
但如果我有两种以上的方法,这会变得相当丑陋。有没有类似于我的原始代码的方法
为此,您可以使用^{} :
可以使用^{} 获取类对象上的实际方法
相关问题 更多 >
编程相关推荐