เมท็อดมหัศจรรย์ในภาษาไพธอน

เมท็อดมหัศจรรย์ในภาษาไพธอน

บทความนี้อธิบายเกี่ยวกับเมท็อดมหัศจรรย์ในไพธอน

YouTube Video

เมท็อดมหัศจรรย์ในภาษาไพธอน

เมท็อดมหัศจรรย์ (เมท็อดพิเศษ) ในไพธอนคือเมท็อดที่ตั้งชื่อเป็นพิเศษเพื่อเพิ่มพฤติกรรมเฉพาะให้กับคลาส เช่น มีลักษณะเฉพาะคือถูกล้อมรอบด้วยขีดล่างสองขีด (dunders) เช่น __init__ และ __str__ ดังนั้น เมท็อดเหล่านี้จึงถูกเรียกว่า dunder methods ด้วย

โดยการกำหนดเมท็อดมหัศจรรย์ คุณสามารถปรับแต่งพฤติกรรมมาตรฐานของคลาสได้ ตัวอย่างเช่น การกำหนด __add__ จะช่วยให้คุณเปลี่ยนพฤติกรรมของโอเปอเรเตอร์ + ได้

เมท็อดมหัศจรรย์สำหรับการกำหนดค่าเริ่มต้นและการแสดงผลเป็นสตริง

__init__: เมท็อดสำหรับกำหนดค่าเริ่มต้น

เมท็อด __init__ คือ constructor ที่ถูกเรียกโดยอัตโนมัติเมื่อสร้างอินสแตนซ์

1class Person:
2    def __init__(self, name, age):
3        self.name = name
4        self.age = age
5
6person = Person("Alice", 30)
7print(person.name)  # Alice

__str__: เมท็อดสำหรับแสดงสตริงที่มนุษย์อ่านเข้าใจง่าย

เมท็อด __str__ จะคืนค่าสตริงที่อ่านง่ายสำหรับมนุษย์ เมท็อดนี้จะถูกเรียกเมื่อใช้ print() และ str()

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def __str__(self):
6        return f"Person: {self.name}"
7
8person = Person("Bob")
9print(person)  # Person: Bob

__repr__: เมท็อดสำหรับแสดงผลที่เน้นการดีบัก

เมท็อด __repr__ จะคืนค่าสตริงเพื่อใช้สำหรับการดีบัก ใช้ร่วมกับ repr() และแสดงผลใน interpreter

1class Person:
2    def __init__(self, name):
3        self.name = name
4
5    def __repr__(self):
6        return f"Person(name={self.name!r})"
7
8person = Person("Eve")
9print(repr(person))  # Person(name='Eve')

การโอเวอร์โหลดโอเปอเรเตอร์ทางคณิตศาสตร์

__add__: โอเปอเรเตอร์ +

โดยการใช้เมท็อดมหัศจรรย์ สามารถโอเวอร์โหลดโอเปอเรเตอร์ทางคณิตศาสตร์ได้ ตัวอย่างเช่น เมท็อด __add__ ช่วยให้สามารถโอเวอร์โหลดโอเปอเรเตอร์ + ได้

 1class Vector:
 2    def __init__(self, x, y):
 3        self.x = x
 4        self.y = y
 5
 6    def __add__(self, other):
 7        return Vector(self.x + other.x, self.y + other.y)
 8
 9    def __repr__(self):
10        return f"Vector({self.x}, {self.y})"
11
12    # Other arithmetic magic methods:
13    # def __sub__(self, other):       # Subtraction (-)
14    # def __mul__(self, other):       # Multiplication (*)
15    # def __truediv__(self, other):   # True division (/)
16    # def __floordiv__(self, other):  # Floor division (//)
17    # def __mod__(self, other):       # Modulo (%)
18    # def __pow__(self, other):       # Exponentiation (**)
19
20v1 = Vector(1, 2)
21v2 = Vector(3, 4)
22print(v1 + v2)  # Vector(4, 6)

เมท็อดมหัศจรรย์ทางคณิตศาสตร์อื่น ๆ มีดังนี้:

เมท็อด โอเปอเรเตอร์
__add__ +
__sub__ -
__mul__ *
__truediv__ /
__floordiv__ //
__mod__ %
__pow__ **

การปรับแต่งโอเปอเรเตอร์เปรียบเทียบ

คุณสามารถโอเวอร์โหลดโอเปอเรเตอร์เปรียบเทียบได้เช่นกัน ตัวอย่างเช่น เมท็อด __eq__ จะโอเวอร์โหลดโอเปอเรเตอร์เท่ากัน

 1class Box:
 2    def __init__(self, volume):
 3        self.volume = volume
 4
 5    def __eq__(self, other):
 6        return self.volume == other.volume
 7
 8    def __lt__(self, other):
 9        return self.volume < other.volume
10
11    # Comparison magic methods:
12    # def __eq__(self, other):  # Equal to (==)
13    # def __ne__(self, other):  # Not equal to (!=)
14    # def __lt__(self, other):  # Less than (<)
15    # def __le__(self, other):  # Less than or equal to (<=)
16    # def __gt__(self, other):  # Greater than (>)
17    # def __ge__(self, other):  # Greater than or equal to (>=)
18
19b1 = Box(100)
20b2 = Box(200)
21
22print(b1 == b2)  # False
23print(b1 < b2)   # True

ยังมีเมท็อดมหัศจรรย์อื่น ๆ ดังต่อไปนี้: เมท็อดมหัศจรรย์เหล่านี้ใช้กำหนดการเปรียบเทียบ เช่น ความเท่ากัน และลำดับระหว่างอ็อบเจ็กต์

โอเปอเรเตอร์ เมท็อดมหัศจรรย์
== __eq__
!= __ne__
< __lt__
<= __le__
> __gt__
>= __ge__

เมท็อดมหัศจรรย์สำหรับประเภทคอนเทนเนอร์

คุณสามารถสร้างคลาสที่ทำงานเลียนแบบลิสต์หรือดิกชันนารีได้

__len__: การนับจำนวนสมาชิก

เมท็อด __len__ คือเมท็อดมหัศจรรย์ที่ใช้คืนค่าจำนวนสมาชิก

1class Basket:
2    def __init__(self, items):
3        self.items = items
4
5    def __len__(self):
6        return len(self.items)
7
8basket = Basket(["apple", "banana"])
9print(len(basket))  # 2

__getitem__: การเข้าถึงด้วยอินเด็กซ์

เมท็อด __getitem__ จะถูกเรียกเมื่อมีการเข้าถึงด้วยอินเด็กซ์

1class Basket:
2    def __init__(self, items):
3        self.items = items
4
5    def __getitem__(self, index):
6        return self.items[index]
7
8basket = Basket(["apple", "banana"])
9print(basket[1])  # banana

__setitem__ และ __delitem__: การเขียนและลบค่า

เมท็อด __setitem__ และ __delitem__ จะถูกเรียกเมื่อมีการเขียนหรือการลบสมาชิก

 1class Basket:
 2    def __init__(self, items):
 3        self.items = items
 4
 5    def __setitem__(self, index, value):
 6        self.items[index] = value
 7
 8    def __delitem__(self, index):
 9        del self.items[index]
10
11basket = Basket(["apple", "banana"])
12basket[1] = "grape"
13del basket[0]
14print(basket.items)  # ['grape']

เมท็อดมหัศจรรย์สำหรับการวนลูป

หากต้องการให้วัตถุถูกวนซ้ำด้วย for loop ได้ ให้กำหนดเมท็อดดังนี้:

__iter__ และ __next__

 1class Counter:
 2    def __init__(self, limit):
 3        self.limit = limit
 4        self.current = 0
 5
 6    def __iter__(self):
 7        return self
 8
 9    def __next__(self):
10        if self.current >= self.limit:
11            raise StopIteration
12        self.current += 1
13        return self.current
14
15for num in Counter(3):
16    print(num)
17# Output:
18# 1
19# 2
20# 3

คอนเท็กซ์เมเนเจอร์ (คำสั่ง with)

ด้วยการกำหนดเมท็อด __enter__ และ __exit__ คุณสามารถดำเนินการก่อนและหลังคำสั่ง with ได้

 1class FileOpener:
 2    def __init__(self, filename):
 3        self.filename = filename
 4
 5    def __enter__(self):
 6        self.file = open(self.filename, 'r')
 7        return self.file
 8
 9    def __exit__(self, exc_type, exc_val, exc_tb):
10        self.file.close()
11
12with FileOpener("example.txt") as f:
13    content = f.read()
14    print(content)

อ็อบเจ็กต์ที่เรียกใช้งานได้: __call__

โดยการกำหนดเมท็อด __call__ จะทำให้อินสแตนซ์ถูกเรียกใช้งานเหมือนฟังก์ชันได้

1class Greeter:
2    def __init__(self, greeting):
3        self.greeting = greeting
4
5    def __call__(self, name):
6        return f"{self.greeting}, {name}!"
7
8hello = Greeter("Hello")
9print(hello("Alice"))  # Hello, Alice!

สรุป

เมท็อดมหัศจรรย์ในไพธอนเป็นวิธีที่มีประสิทธิภาพในการเพิ่มพฤติกรรมที่เป็นธรรมชาติและเข้าใจง่ายให้กับคลาส แต่ละเมท็อดมีวัตถุประสงค์ที่ชัดเจน และการนำมาใช้อย่างถูกต้องช่วยให้คุณเขียนโค้ดที่ยืดหยุ่นและเป็น Pythonic มากขึ้น

เมท็อดมหัศจรรย์เปรียบเสมือน 'อินเทอร์เฟซที่มองไม่เห็น' ที่ช่วยควบคุมการทำงานและการโต้ตอบของอ็อบเจ็กต์ในไพธอนเบื้องหลัง

คุณสามารถติดตามบทความข้างต้นโดยใช้ Visual Studio Code บนช่อง YouTube ของเรา กรุณาตรวจสอบช่อง YouTube ด้วย

YouTube Video