开始使用免费开始使用

检查类是否相同

在上一个练习中,您定义了一个带有 number 属性的 BankAccount 类,并用它来比较对象。但如果您把一个 BankAccount 对象与另一个也有 number 属性的不同类的对象进行比较,可能会得到意料之外的结果。

例如,考虑下面两个类:


class Phone:
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == \
               other.number

pn = Phone(873555333)

class BankAccount:
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        return self.number == \
               other.number

acct = BankAccount(873555333)

运行 acct == pn 会返回 True,尽管它是在比较电话号码与银行账户号。

良好的做法是:在 __eq__() 方法中检查传入对象的类,确保比较是合理的。

本练习是课程的一部分

Python 面向对象编程入门

查看课程

练习说明

  • 修改 BankAccount 的定义:只有当 number 属性相同,且传入的两个对象的 type() 相同,才返回 True
  • 检查 acctpn 是否相等。

交互式实操练习

通过完成这段示例代码来试试这个练习。

class BankAccount:
  def __init__(self, number, balance=0):
    self.number, self.balance = number, balance
      
  def withdraw(self, amount):
    self.balance -= amount 

  # Modify to add a check for the class type
  def __eq__(self, other):
    return (self.number == other.number) ____

acct = BankAccount(873555333)
pn = Phone(873555333)

# Check if the two objects are equal
print(____)
编辑并运行代码