【发布时间】:2011-07-04 06:41:19
【问题描述】:
是否可以在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
这意味着我必须制作这本词典,但真的有必要吗?
【问题讨论】:
-
只要您有一组可管理的运算符,字典就可以了。