首页 > 解决方案 > 像 __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 有什么特别之处吗?

标签: python

解决方案


这个简单的片段正在工作:

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 ========================================================================================

也许你可以摘录你的代码


推荐阅读