【问题标题】:Looping over operator循环运算符
【发布时间】:2021-04-09 12:47:05
【问题描述】:

我正在为类型类编写测试,我想知道是否有一种循环和更改运算符的方法?所以循环[+, -, *, / , // ]

所以我想做的是:

for op in operators:
 assert 2 op my_type == 2 op my_type.num_atr # op being the operator +, - etc 

所以这将与

相同
assert 2 + my_type == 2 + my_type.num_atr
assert 2 - my_type == 2 - my_type.num_atr
assert 2 * my_type == 2 * my_type.num_atr
# ....

这有可能吗?我知道这有点只是语法糖,并且没有太多的运算符,但这会使同时更改所有测试更快。

【问题讨论】:

    标签: python python-3.x operators


    【解决方案1】:

    operator 模块怎么样?或者简单地将操作写成函数。

    import operator
    
    for op in (
        operator.add,
        operator.sub,
        operator.mul,
        operator.div,
        operator.floordiv,
    ):
        assert op(2, my_type) == op(2, my_type.num_atr)  # op being the operator +, - etc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多