運算子多載:比較物件

Python 物件導向程式設計入門

George Boorman

Curriculum Manager, DataCamp

物件相等性

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

customer1 = Customer("Maryam Azar", 3000)
customer2 = Customer("Maryam Azar", 3000)

# Check for equality customer1 == customer2
False
Python 物件導向程式設計入門

物件相等性

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

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)

customer1 == customer2
False
Python 物件導向程式設計入門

變數是參考

customer_one = Customer("Maryam Azar", 3000, 123)
customer_two = Customer("Maryam Azar", 3000, 123)

print(customer_one)
<__main__.Customer at 0x1f8598e2e48>
print(customer_two)
<__main__.Customer at 0x1f8598e2240>
  • print() 輸出指的是變數所指向的記憶體位置
  • == 比較的是參考,而非資料
Python 物件導向程式設計入門

自訂比較

# Two different lists containing the same data
list_one = [1,2,3]
list_two = [1,2,3]

list_one == list_two
True
Python 物件導向程式設計入門

__eq__() 方法

  • 當以 == 比較該類別的 2 個物件時會呼叫 __eq__()
  • 接受 2 個引數:selfother(要比較的物件)
  • 回傳布林值
Python 物件導向程式設計入門

__eq__() 方法

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

# Will be called when == is used def __eq__(self, other):
# Printout print("__eq__() is called") # Returns True if all attributes match return (self.acc_id == other.acc_id) and (self.name == other.name)
Python 物件導向程式設計入門

物件的比較

# Two equal objects
customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(123, "Maryam Azar")

customer1 == customer2
__eq__() is called
True
# Two unequal objects - different ids
customer1 = Customer(123, "Maryam Azar")
customer2 = Customer(456, "Maryam Azar")

customer1 == customer2
__eq__() is called
False
Python 物件導向程式設計入門

檢查型別

  • 如果兩個不同類別的物件有相同屬性與值會怎樣?
    • Python 會判定它們相等
class Customer:
    def __init__(self, acc_id, name):
        self.acc_id, self.name = idacc_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 物件導向程式設計入門

其他比較運算子

運算子 方法
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • 可在類別內自訂這些方法
Python 物件導向程式設計入門

一起來練習吧!

Python 物件導向程式設計入門

Preparing Video For Download...