Python Magic Methods



Magic methods (หรือ dunder methods — double underscore) คือเมท็อดชื่อพิเศษที่ขึ้นต้นและลงท้ายด้วย __ Python เรียกมันให้อัตโนมัติในสถานการณ์ต่าง ๆ เราเคยเจอ __init__ มาแล้ว บทนี้จะดูตัวอื่นที่ทำให้อ็อบเจกต์ของเราใช้งานได้เป็นธรรมชาติเหมือนชนิดข้อมูลในตัว

__str__ กับ __repr__

ทั้งคู่คืนข้อความแทนอ็อบเจกต์ แต่ใช้คนละที่

  • __str__ — สำหรับคนอ่าน ใช้ตอน print() และ str()
  • __repr__ — สำหรับ developer ใช้ตอนพิมพ์ในเชลล์ ใน list และตอน debug ควรเขียนให้ก๊อปไปสร้างอ็อบเจกต์ใหม่ได้
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __str__(self):
        return f"({self.x}, {self.y})"

    def __repr__(self):
        return f"Point({self.x}, {self.y})"


p = Point(3, 4)
print(p)          # (3, 4)          ← __str__
print(str(p))     # (3, 4)          ← __str__
print(repr(p))    # Point(3, 4)     ← __repr__
print([p, p])     # [Point(3, 4), Point(3, 4)]  ← __repr__

points = [Point(1, 2), Point(5, 6)]
print(points)     # ใช้ __repr__ ของแต่ละตัว

ถ้าจะเขียนแค่ตัวเดียว ให้เขียน __repr__ เพราะ Python จะใช้มันแทน __str__ เมื่อ __str__ ไม่มี

__eq__: เปรียบเทียบความเท่ากัน

ปกติ == ระหว่างอ็อบเจกต์เช็คว่าเป็นตัวเดียวกันในหน่วยความจำไหม ไม่ได้เช็คค่าข้างใน

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y


a = Point(1, 2)
b = Point(1, 2)
print(a == b)   # False  — คนละอ็อบเจกต์

นิยาม __eq__ เพื่อเทียบด้วยค่า

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y


a = Point(1, 2)
b = Point(1, 2)
print(a == b)   # True

ถ้านิยาม __eq__ แล้วอยากให้อ็อบเจกต์ใช้เป็นคีย์ของ dict หรือใส่ใน set ได้ ต้องนิยาม __hash__ ด้วย (เพิ่มเมท็อดนี้เข้าไปในคลาส Point)

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __hash__(self):
        return hash((self.x, self.y))


points = {Point(1, 2), Point(1, 2), Point(3, 4)}
print(len(points))   # 2 — Point(1, 2) สองตัวถือเป็นตัวเดียวกัน

__len__: รองรับ len()

class Playlist:
    def __init__(self):
        self.songs = []

    def add(self, song):
        self.songs.append(song)

    def __len__(self):
        return len(self.songs)


pl = Playlist()
pl.add("เพลง A")
pl.add("เพลง B")
print(len(pl))   # 2

__getitem__: รองรับ [] และการวนลูป

class Deck:
    def __init__(self):
        self.cards = ["A", "K", "Q", "J", "10"]

    def __getitem__(self, index):
        return self.cards[index]

    def __len__(self):
        return len(self.cards)


deck = Deck()
print(deck[0])     # A
print(deck[-1])    # 10
print(deck[1:3])   # ['K', 'Q']

for card in deck:  # วนได้เพราะมี __getitem__
    print(card)

__add__ และตัวดำเนินการอื่น

นิยามว่า +, -, * ควรทำอะไรกับอ็อบเจกต์ของเรา

class Money:
    def __init__(self, baht):
        self.baht = baht

    def __add__(self, other):
        return Money(self.baht + other.baht)

    def __sub__(self, other):
        return Money(self.baht - other.baht)

    def __mul__(self, factor):
        return Money(self.baht * factor)

    def __repr__(self):
        return f"{self.baht:,.2f} บาท"


wallet = Money(500)
income = Money(1200)

print(wallet + income)     # 1,700.00 บาท
print(income - wallet)     # 700.00 บาท
print(wallet * 3)          # 1,500.00 บาท
magic methodตัวดำเนินการ
__add__+
__sub__-
__mul__*
__truediv__/
__lt__<
__gt__>
__le__<=

__lt__: ทำให้ sort ได้

นิยาม __lt__ (less than) แล้ว sorted() และ min()/max() ใช้กับอ็อบเจกต์เราได้

class Student:
    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa

    def __lt__(self, other):
        return self.gpa < other.gpa

    def __repr__(self):
        return f"{self.name}({self.gpa})"


students = [Student("A", 3.2), Student("B", 3.9), Student("C", 2.8)]
print(sorted(students))       # [C(2.8), A(3.2), B(3.9)]
print(max(students))          # B(3.9)

__call__: ทำให้อ็อบเจกต์เรียกได้เหมือนฟังก์ชัน

class Multiplier:
    def __init__(self, factor):
        self.factor = factor

    def __call__(self, value):
        return value * self.factor


double = Multiplier(2)
triple = Multiplier(3)

print(double(10))   # 20
print(triple(10))   # 30

ตัวอย่างรวม: เวกเตอร์ 2 มิติ

import math


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __abs__(self):
        return math.hypot(self.x, self.y)     # ความยาวเวกเตอร์

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v1 = Vector(3, 4)
v2 = Vector(1, 2)

print(v1 + v2)      # Vector(4, 6)
print(v1 * 2)       # Vector(6, 8)
print(abs(v1))      # 5.0
print(v1 == Vector(3, 4))   # True

เช็คความเข้าใจก่อนข้ามบท

  • อธิบายได้ว่า magic method ทำให้อ็อบเจกต์ทำงานกับ syntax ปกติของ Python ได้
  • แยกการใช้งาน __str__ กับ __repr__ ได้
  • ลองเพิ่ม __eq__ ให้คลาสของตัวเองเพื่อเทียบความเท่ากันจากข้อมูลภายใน

สรุป

  • Magic methods ให้ Python เรียกอัตโนมัติในสถานการณ์ต่าง ๆ
  • __str__/__repr__ คุมข้อความ, __eq__ เทียบค่า, __len__ รองรับ len()
  • __getitem__ รองรับ [] และวนลูป, __add__ ฯลฯ รองรับตัวดำเนินการ
  • __lt__ ทำให้ sorted() ใช้ได้, __call__ ทำให้อ็อบเจกต์เรียกเหมือนฟังก์ชัน

บทถัดไปว่าด้วย @property, @classmethod และ @staticmethod