การ Overload ตัวดำเนินการ ==
ตัวดำเนินการในตัวของ Python นั้นมีประโยชน์มาก โดยเฉพาะเมื่อต้องเปรียบเทียบ instance ของคลาส เมื่อสร้างคลาส เราสามารถใช้ magic method เพื่อเปลี่ยนพฤติกรรมของตัวดำเนินการเหล่านี้ได้ ในแบบฝึกหัดนี้ คุณจะ overload ตัวดำเนินการ == เพื่อตรวจสอบว่า instance สองตัวของคลาส Computer เท่ากันหรือไม่
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Object-Oriented Programming ใน Python ระดับกลาง
คำแนะนำการฝึกหัด
- กำหนด magic method เพื่อ overload ตัวดำเนินการ
== - เปรียบเทียบ attribute
device_idของselfและotherภายใน magic method เพื่อตรวจสอบว่า instance ทั้งสองเท่ากันหรือไม่ - ตรวจสอบว่า
pre_upgrade_computerกับpost_upgrade_computerเท่ากันหรือไม่ แล้วพิมพ์ผลลัพธ์
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
class Computer:
def __init__(self, device_id, storage):
self.device_id = device_id
self.storage = storage
# Overload the == operator using a magic method
def ____(self, other):
# Return a boolean based on the value of device_id
____ self.____ == other.____
pre_upgrade_computer = Computer("Y391Hky6", 256)
post_upgrade_computer = Computer("Y391Hky6", 1024)
# Create two instances of Computer, compare using ==
print(____ == ____)