繼承下的比較與字串表示

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):
        # Returns True if the objects have the same attributes
        # and are of the same type
        return (self.acc_id == other.acc_id) and (self.name == other.name)\
            and (type(self) == type(other))
Python 物件導向程式設計入門

在繼承下比較物件

 

 

 

                               

    若其中一個物件從另一個物件的類別「繼承」,該怎麼辦?

Python 物件導向程式設計入門

往來與儲蓄帳戶

SavingsAccount 繼承自 BankAccount

Python 物件導向程式設計入門

__eq__ 在父類別與子類別中

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

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

    # Define __eq__ that returns True 
    # if the number attributes are equal 
    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

    # Define __eq__ that returns True 
    # if the number attributes are equal 
    def __eq__(self, other):
        print("SavingsAccount __eq__() called")
        return self.number == other.number 
Python 物件導向程式設計入門

比較父類別與子類別物件

ba = BankAccount(123, 10000)
sa = SavingsAccount(456, 2000, 0.05)
# Compare the two objects
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]'
  • 較非正式,給終端使用者
  • 字串(str)表示

__repr__()

  • repr(obj)、在主控台列印
repr(np.array([1,2,3]))
'array([1,2,3])'
np.array([1,2,3])
array([1, 2, 3])
  • 較正式,給開發者
  • 可再現(reproducible)的表示(representation)
  • print() 的後備選項
Python 物件導向程式設計入門

實作:repr

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

    def __repr__(self):

# Notice the '...' around name return f"Customer('{self.name}', {self.balance})"
cust = Customer("Maryam Azar", 3000) # Will implicitly call __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)

# Will implicitly call __str__()
print(cust)
Customer:
  name: Maryam Azar
  balance: 3000
Python 物件導向程式設計入門

一起來練習吧!

Python 物件導向程式設計入門

Preparing Video For Download...