การโอเวอร์โหลดโอเปอเรเตอร์: การเปรียบเทียบ

การเขียนโปรแกรมเชิงวัตถุใน 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)

 

 

  • __eq__() ถูกเรียกเมื่อเปรียบเทียบออบเจกต์ 2 ตัวด้วย ==
  • รับอาร์กิวเมนต์ 2 ตัว คือ self และ other ซึ่งเป็นออบเจกต์ที่ต้องการเปรียบเทียบ
  • คืนค่าเป็น Boolean
การเขียนโปรแกรมเชิงวัตถุใน 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__()
  • __hash__() ใช้เพื่อนำออบเจกต์ไปเป็นคีย์ของ dictionary และใช้ใน set
การเขียนโปรแกรมเชิงวัตถุใน Python

มาฝึกกันเถอะ!

การเขียนโปรแกรมเชิงวัตถุใน Python

Preparing Video For Download...