運算子多載:比較

Python 物件導向程式設計

Alex Yarosh

Content Quality Analyst @ DataCamp

物件相等性

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


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

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

物件相等性

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

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
customer1 == customer2
False
Python 物件導向程式設計

變數是參照

customer1 = Customer("Maryam Azar", 3000, 123)
customer2 = Customer("Maryam Azar", 3000, 123)
print(customer1)
<__main__.Customer at 0x1f8598e2e48>
print(customer2)
<__main__.Customer at 0x1f8598e2240>
Python 物件導向程式設計

自訂比較

import numpy as np

# Two different arrays containing the same data
array1 = np.array([1,2,3])
array2 = np.array([1,2,3])

array1 == array2
True
Python 物件導向程式設計

多載 __eq__()

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

# Will be called when == is used def __eq__(self, other):
# Diagnostic printout print("__eq__() is called") # Returns True if all attributes match return (self.id == other.id) and \ (self.name == other.name)

 

 

  • 使用 == 比較該類別的 2 個物件時會呼叫 __eq__()
  • 接受 2 個引數:selfother(要比較的物件)
  • 回傳布林值
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 物件導向程式設計

其他比較運算子

運算子 方法
== __eq__()
!= __ne__()
>= __ge__()
<= __le__()
> __gt__()
< __lt__()
  • 要把物件用作字典鍵或放進 set,需實作 __hash__()
Python 物件導向程式設計

一起來練習吧!

Python 物件導向程式設計

Preparing Video For Download...