我需要transaction
和other_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
用@dataclass注释
LedgerTransaction
,让解释器为您生成方法您需要比较每个字段,因此like-equal应该是:
现在,您只是比较对象的引用,就像它们在内存中的地址一样,而不是对象的实际内容
相关问题 更多 >
编程相关推荐