继承比较与字符串表示

Python 面向对象编程入门

George Boorman

Curriculum Manager, DataCamp

比较不同类的对象

class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = acc_id, name

    def __eq__(self, other):
        # 当对象属性相同且类型相同返回 True
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Python 面向对象编程入门

带继承的对象比较

 

 

 

                               

    如果一个对象从另一个对象的类中继承,会怎样?

Python 面向对象编程入门

银行账户与储蓄账户

储蓄账户继承自活期账户

Python 面向对象编程入门

父类/子类中的 __eq__

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

    def withdraw(self, amount):
        self.balance -= amount 

    # 定义 __eq__:当号码相等时返回 True
    def __eq__(self, other):
        print("BankAccount __eq__() called")
        return self.number == other.number 
class SavingsAccount(BankAccount):
    def __init__(self, number, balance, interest_rate):
        BankAccount.__init__(self, number,
                             balance)
          self.interest_rate = interest_rate

    # 定义 __eq__:当号码相等时返回 True
    def __eq__(self, other):
        print("SavingsAccount __eq__() called")
        return self.number == other.number 
Python 面向对象编程入门

比较父类与子类对象

ba = BankAccount(123, 10000)
sa = SavingsAccount(456, 2000, 0.05)
# 比较两个对象
ba == sa
SavingsAccount __eq__() called
False
sa == ba
SavingsAccount __eq__() called
False
Python 面向对象编程入门

打印对象

class Customer:
    def __init__(self, name, balance):
        self.name, self.balance = name, balance 

cust = Customer("Maryam Azar", 3000)
print(cust)
<__main__.Customer at 0x1f8598e2240>




a_list = [1,2,3]
print(a_list)
[1, 2, 3]
Python 面向对象编程入门

__str__()

  • print(obj), str(obj)
print(np.array([1,2,3]))
[1 2 3]
str(np.array([1,2,3]))
'[1 2 3]'
  • 非正式,面向最终用户
  • 字符串表示

__repr__()

  • repr(obj),控制台打印
repr(np.array([1,2,3]))
'array([1,2,3])'
np.array([1,2,3])
array([1, 2, 3])
  • 正式,面向开发者
  • 可复现的表示
  • print() 的后备
Python 面向对象编程入门

实现:repr

class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance 

    def __repr__(self):

# 注意 name 周围的引号 return f"Customer('{self.name}', {self.balance})"
cust = Customer("Maryam Azar", 3000) # 会隐式调用 __repr__() cust
Customer('Maryam Azar', 3000)
Python 面向对象编程入门

实现:str

class Customer:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
    def __str__(self):
        cust_str = f"""
        Customer:
            name: {self.name}
            balance: {self.balance}
            """
        return cust_str
cust = Customer("Maryam Azar", 3000)

# 会隐式调用 __str__()
print(cust)
Customer:
  name: Maryam Azar
  balance: 3000
Python 面向对象编程入门

开始练习吧!

Python 面向对象编程入门

Preparing Video For Download...