python将字符串转换为运算符

时间:2011-02-25 12:17:44

标签: python string function

是否可以在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

这意味着我必须制作这本词典,但这是否真的有必要?

3 个答案:

答案 0 :(得分:4)

您可以使用eval动态构建一段Python代码并执行它,但除此之外没有真正的替代方案。然而,基于字典的解决方案更加优雅和安全。

除此之外,它真的 坏吗?为什么不缩短它......

return operator_dict[operator_string](left_value, right_value)

答案 1 :(得分:2)

指定问题的方式我不明白为什么你不能将operator.le传递给函数而不是“> =”。

如果这个operator_string来自数据库或文件或某些东西,或者你是否在代码中传递了它?

bar.foo('x', operator.le , 10)

你只是想要一个方便的速记吗?然后你可以做类似的事情:

from operator import le
bar.foo('x', le, 10)

如果这里真正的问题是你有来自数据库或数据文件的代码或业务规则那么你可能真的需要编写一个小的解析器来将你的输入映射到这些对象然后你可以看看使用像pyparsing,ply,codetalker等库。

答案 2 :(得分:0)

#This is very simple to do with eval()

score=1
trigger_conditon=">="
trigger_value=4

eval(f"{score}{trigger_conditon}{trigger_value}")

#luckily fstring also takes care of int/float or relavaent datatype

operator_str="ge"
import operator
eval(f"operator.{operator_str}({score},{trigger_value})")