บทที่ 4.4: Magic Methods (Dunder Methods เช่น str, repr, len)
เอกสารนี้อธิบายเกี่ยวกับการใช้งาน Magic Methods หรือ Dunder Methods (Double Underscore Methods) ในภาษา Python สำหรับการกำหนดพฤติกรรมของ Object เมื่อทำงานร่วมกับ Built-in Functions และ Operators
1. Magic Methods (Dunder Methods) คืออะไร
Magic Methods คือเมธอดพิเศษที่มีเครื่องหมาย __ นำหน้าและต่อท้ายชื่อเมธอด โดยระบบของ Python จะเรียกใช้งานเมธอดเหล่านี้โดยอัตโนมัติเมื่อ Object ถูกนำไปใช้ร่วมกับคำสั่งหรือตัวดำเนินการเฉพาะ
2. เมธอดแปลงเป็นข้อความ (__str__ และ __repr__)
__str__: คืนค่าข้อความสำหรับแสดงผลแก่ผู้ใช้งานทั่วไป (เรียกใช้ผ่านprint()หรือstr())__repr__: คืนค่าข้อความเชิงเทคนิคสำหรับนักพัฒนาใช้ในการตรวจสอบ/Debug (เรียกใช้ผ่านrepr())
class Book:
def __init__(self, title, author, price):
self.title = title
self.author = author
self.price = price
def __str__(self):
return f"หนังสือ '{self.title}' โดย {self.author}"
def __repr__(self):
return f"Book(title='{self.title}', author='{self.author}', price={self.price})"
book = Book("Python Core", "Sebastian", 450)
print(str(book)) # Output: หนังสือ 'Python Core' โดย Sebastian
print(repr(book)) # Output: Book(title='Python Core', author='Sebastian', price=450)
3. เมธอดจัดการความยาวและการเข้าถึงข้อมูล (__len__ และ __getitem__)
__len__: กำหนดค่าที่จะคืนกลับเมื่อใช้ฟังก์ชันlen()กับ Object__getitem__: อนุญาตให้เข้าถึงข้อมูลภายใน Object ผ่าน Index หรือ Key แบบobj[index]
class Library:
def __init__(self, books):
self.books = books
def __len__(self):
return len(self.books)
def __getitem__(self, index):
return self.books[index]
my_library = Library(["Python 101", "Data Structure", "Web Dev"])
# เรียกใช้งานผ่าน __len__
print(len(my_library)) # Output: 3
# เรียกใช้งานผ่าน __getitem__
print(my_library[0]) # Output: Python 101
4. เมธอดสำหรับการเปรียบเทียบและคณิตศาสตร์ (Operators)
ช่วยให้ Object สามารถเปรียบเทียบค่าหรือคำนวณทางคณิตศาสตร์ร่วมกันได้
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
# เท่ากับ (==)
def __eq__(self, other):
return self.price == other.price
# น้อยกว่า (<)
def __lt__(self, other):
return self.price < other.price
# บวก (+)
def __add__(self, other):
return self.price + other.price
p1 = Product("Mouse", 500)
p2 = Product("Keyboard", 1200)
print(p1 == p2) # Output: False
print(p1 < p2) # Output: True
print(p1 + p2) # Output: 1700