是否有int / str / float等效项在python中用于'==,!=,> =等符号? [重复]

问题描述 投票:0回答:1

我正在尝试编写动态python脚本,在其中将if语句存储在数据库中。例如:

op='=='
stat1='4'
stat=int(stat1)
if stat==4: # Works
if stat + op + stat: # Does not Work

是否存在格式化op的解决方案,以便它可以被python读取?

python if-statement
1个回答
1
投票

使用operator 模块获取二进制操作的相应功能:

operator

您将像这样评估它们:

import operator

conversions = {
    '==': operator.eq,
    '+': operator.add
    ...
}

不推荐使用的另一种方法是使用基础的特殊方法名称来执行操作:

op = conversions['==']
if op(stat, stat1):
    ...

现在评估代码时:

conversions = {
    '==': '__eq__',
    '!=': '__ne__',
    '>=': '__ge__',
    ...
}

要创建完整的转换列表,请使用op = conversions['=='] if getattr(stat, op)(stat1): ... 网站获取二进制运算的方法名称-诸如加法的算术运算和大于等的逻辑运算。

© www.soinside.com 2019 - 2024. All rights reserved.