python - 像 __rsub__ 这样的 Dunder 方法在 pytest 中不起作用
问题描述
可以说我有一堂课Foo
。我希望能够做类似的事情
a = Foo()
print(10 - a)
我已经定义了__sub__
和__rsub__
方法,Foo
当我在控制台中对其进行测试时它们会起作用。
但是,当我在 Pytest 中使用它时,它不断给我TypeError: unsupported operand type(s) for -: 'int' and 'Foo'
.
它也忽略__rdiv__
,但不是__radd__
or __rmul__
。Pytest 有什么特别之处吗?
解决方案
这个简单的片段正在工作:
class Foo:
def __init__(self, x):
self.x = x
def __sub__(self, other):
return self.x - other
def __rsub__(self, other):
return other - self.x
from foo import Foo
def test_a():
assert Foo(5) - 10 == -5
def test_b():
assert 10 - Foo(5) == 5
======================================================================================= test session starts =======================================================================================
platform darwin -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: xxx
collected 2 items
test_foo.py .. [100%]
======================================================================================== 2 passed in 0.01s ========================================================================================
也许你可以摘录你的代码
推荐阅读
- haskell - 代数数据类型字段名称无法识别
- pandas - 将制表符和换行符分隔的字符串转换为 pandas 数据框
- java - Java - 防止 HashMap 影响原始值
- cabal - 如何在 cabal 或堆栈文件中指定 ghc 版本
- powershell - IIS 的 Powershell:“Foreach”循环失败
- java - Spring Data CrudRepository 类中的这个 S 参数是什么?
- try-catch - “catch”后面的部分叫什么?
- javascript - 无法根据数字范围限制正则表达式
- bash - 在 Vim 中运行 bashscript/Unix 行
- python - 使用 NULL 值评估元组的字符串表示