在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
这意味着我必须做这本词典,但真的有必要吗?