是否可以在python中将字符串转换为运算符?
我想将条件传递给函数
理想的情况是这样的:
def foo(self, attribute, operator_string, right_value):
left_value = getattr(self, attribute)
if left_value get_operator(operator_string) right_value:
return True
else:
return False
bar.x = 10
bar.foo('x', '>', 10)
[out] False
bar.foo('x', '>=', 10)
[out] True
我可以制作一个字典,其中键是字符串,值是运算符模块的功能.
我将不得不稍微更改foo的定义:
operator_dict = {'>', operator.lt,
'>=', operator.le}
def foo(self, attribute, operator_string, right_value):
left_value = getattr(self, attribute)
operator_func = operator_dict[operator_string]
if operator_func(left_value, right_value):
return True
else:
return False
这意味着我必须制作这本词典,但这真的有必要吗?
解决方法:
您可以使用eval动态地构建一段Python代码并执行它,但是除此之外,没有真正的选择.但是,基于字典的解决方案更加优雅和安全.
除此之外,真的那么糟糕吗?为什么不缩短一点……
return operator_dict[operator_string](left_value, right_value)
标签:python,function,string
来源: https://codeday.me/bug/20191011/1893403.html