如何在python中重写equal?

2024-06-28 19:50:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要transactionother_transaction相等。有人能看到我遗漏了什么吗

    def test_eq_LedgerTransaction():
>       assert LedgerTransaction.__eq__(transaction, equal_transaction) is True          
E       assert False is True
E        +  where False = <function LedgerTransaction.__eq__ at 0x7f49c3183550>(transaction, equal_transaction)
E        +    where <function LedgerTransaction.__eq__ at 0x7f49c3183550> = LedgerTransaction.__eq__

代码

class LedgerTransaction():
    def __init__(self, date: str, payee: str, amount: float):
        self.date = date
        self.payee = payee
        self.amount = float(amount)

    def __eq__(self, other):
        return self == other

    def __repr__(self):
        return f'Transaction:{self.date, self.payee, self.amount}'

    def __hash__(self):
        return hash((self.date, self.payee, self.amount))


# Tests
import pytest


@pytest.fixture
def transaction():
    return LedgerTransaction("2021/12/31", "transaction", 5.0)


@pytest.fixture
def equal_transaction():
    return LedgerTransaction("2021/12/31", "transaction", 5.0)


@pytest.fixture
def other_transaction():
    return LedgerTransaction("2021/12/31", "peach", 5.0)


def test_eq_LedgerTransaction():
    assert LedgerTransaction.__eq__(transaction, equal_transaction) is True
    assert LedgerTransaction.__eq__(transaction, other_transaction) is False

Tags: selftruedatereturnpytestisdefassert
2条回答

@dataclass注释LedgerTransaction,让解释器为您生成方法

您需要比较每个字段,因此like-equal应该是:

    def __eq__(self, other):
        return self.date == other.date and self.payee == other.payee and self.amount == other.amount

现在,您只是比较对象的引用,就像它们在内存中的地址一样,而不是对象的实际内容

相关问题 更多 >