python将字符串转换为运算符 [英] python convert a string to an operator

查看:1011
本文介绍了python将字符串转换为运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在python中将字符串转换为运算符?
我想将一个条件传递给一个函数



理想情况下,它看起来像这样:

 def foo(self,attribute,operator_string,right_value):
left_value = getattr(self,attribute)
如果为left_value get_operator(operator_string)right_value:
返回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 ]
如果operator_func(left_value,right_value):
返回True
else:
返回False

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

解决方案

您可以使用 eval 动态构建一段Python代码并执行它,但除此之外,没有其他选择。然而,基于字典的解决方案更加优雅和安全。 除此之外, 真的不好吗?为什么不缩短它...

  return operator_dict [operator_string](left_value,right_value)


Is it possible to convert a string to an operator in python? I would like to pass a condition to a function

Ideally it would look like this:

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

I could make a dictionary where keys are strings and values are functions of the operator module. I would have to change foo definition slightly:

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

This means I have to make this dictionary, but is it really necessary?

解决方案

You can use eval to dynamically build a piece of Python code and execute it, but apart from that there are no real alternatives. The dictionary-based solution is much more elegant and safe, however.

Apart from that, is it really that bad? Why not shorten it a bit …

return operator_dict[operator_string](left_value, right_value)

这篇关于python将字符串转换为运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆