Python将字符串转换为操作符

2 投票
3 回答
13384 浏览
提问于 2025-04-16 12:31

在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
#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})")

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

3

根据问题的描述,我不明白为什么你不能把 operator.le 这个操作符传给函数,而非使用 ">="。

这个 operator_string 是从数据库、文件之类的地方来的,还是你在代码里传来传去的?

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

你是不是只是想要一个方便的简写?那你可以试试这样做:

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

如果真正的问题是你有一些代码或者业务规则是从数据库或数据文件中来的,那你可能需要考虑写一个小的解析器,把你的输入转换成这些对象,然后你可以看看使用像 pyparsing、ply、codetalker 这样的库。

4

你可以用 eval 来动态生成一段 Python 代码并执行它,但除了这个方法,实际上没有什么好的替代方案。不过,基于字典的解决方案要更优雅和安全得多。

除此之外,这真的有那么糟糕吗?为什么不把它缩短一点呢……

return operator_dict[operator_string](left_value, right_value)

撰写回答