使用 functools.total_ordering 进行比较

use*_*227 0 python python-3.x

我有下面的代码...

class BankAccount:
    """ Simple BankAccount class """

    def __init__(self, balance=0):
        """Initialize account with balance"""
        self.balance = balance

    def deposit(self, amount):
        """Deposit amount to this account"""
        self.balance += amount

    def withdraw(self, amount):
        """Withdraw amount from this account"""
        self.balance -= amount

    def __str__(self):
        return 'Account with a balance of {}'.format(self.balance)

    def __repr__(self):
        return "BankAccount(balance={})".format(self.balance)

    def __bool__(self):
        if self.balance > 0:
            return True
        else:
            return False
Run Code Online (Sandbox Code Playgroud)

该代码基本上是一个简单的银行账户模拟器。我想实现对 BankAccount 对象的比较,以便可以根据它们的余额来比较实例。我想使用 functools.total_ordering 来做到这一点。预期输出低于...

    account1 = BankAccount(100)
    account2 = BankAccount()
    account3 = BankAccount(100)
    account1 == account2
False
    account1 == account3
True
    account1 != account3
False
    account1 < account2
False
    account1 >= account2
True
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

mra*_*777 6

您只需要定义至少一个函数:

__lt__(), __le__(), __gt__(), or __ge__() 此外,该类应该提供一个__eq__()方法。

然后你像这样使用装饰器:

from functools import total_ordering

@total_ordering
class BankAccount:
""" Simple BankAccount class """

   def __init__(self, balance=0):
    """Initialize account with balance"""
       self.balance = balance
   def __lt__(self, other):
       return self.balance  < other.balance 
   def __eq__(self,other):
       return self.balance == other.balance
Run Code Online (Sandbox Code Playgroud)