循环运算符
Looping over operator
我正在为类型 class 编写测试,我想知道是否有循环和更改运算符的方法?所以循环 [+, -, *, / , // ]
所以我想做的是:
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
# ....
这有可能吗?我知道这在某种程度上只是语法糖并且没有太多的运算符,但这会使同时更改所有测试更快。
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
我正在为类型 class 编写测试,我想知道是否有循环和更改运算符的方法?所以循环 [+, -, *, / , // ]
所以我想做的是:
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
# ....
这有可能吗?我知道这在某种程度上只是语法糖并且没有太多的运算符,但这会使同时更改所有测试更快。
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