使用functools.total_ordering进行比较

时间:2018-07-29 20:03:05

标签: 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

该代码基本上是一个简单的银行帐户模拟器。我想对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

我该怎么做?

1 个答案:

答案 0 :(得分:3)

您只需要定义至少一个功能:

__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