Mga Magic Method sa Python

Mga Magic Method sa Python

Ipinaliwanag ng artikulong ito ang mga magic method sa Python.

YouTube Video

Mga Magic Method sa Python

Ang mga magic method (special methods) sa Python ay mga espesyal na pinangalanang pamamaraan na ginagamit upang bigyan ng natatanging asal ang mga klase. Halimbawa, ang katangian ng mga ito ay pinalilibutan ng dobleng underscore (dunder), tulad ng __init__ at __str__. Kaya, tinatawag din silang mga dunder methods.

Sa pamamagitan ng pagde-define ng mga magic method, maaari mong i-customize ang karaniwang asal ng mga klase. Halimbawa, ang pagde-define ng __add__ ay nagbibigay-daan upang mabago ang asal ng operator na +.

Mga Magic Method para sa Initialization at String Representation

__init__: Paraan ng Initialization

Ang __init__ method ay isang constructor na awtomatikong tinatawag kapag nilikha ang isang instance.

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__: Human-Readable na String Representation

Ang __str__ method ay nagbabalik ng string representation na madaling basahin ng tao. Ito ay tinatawag ng print() at 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__: Debug-Oriented na String Representation

Ang __repr__ method ay nagbibigay ng string representation para sa debugging. Ito ay ginagamit ng repr() at kapag ipinapakita sa 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')

Overloading ng mga Arithmetic Operator

__add__: Operator na +

Sa paggamit ng mga magic method, maaaring i-overload ang mga arithmetic operator. Halimbawa, pinapayagan ng __add__ na i-overload ang operator na +.

 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)

Ilan pa sa iba pang arithmetic magic method ay ang mga sumusunod:.

Method Operator
__add__ +
__sub__ -
__mul__ *
__truediv__ /
__floordiv__ //
__mod__ %
__pow__ **

Pag-customize ng mga Comparison Operator

Maaari mo ring i-overload ang mga comparison operator. Halimbawa, ang __eq__ method ay nag-o-overload ng equality operator.

 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

Mayroon ding mga sumusunod na magic method:. Ang mga magic method na ito ay nagtatakda ng mga paghahambing tulad ng pagkakapantay-pantay at pagkakasunud-sunod sa pagitan ng mga object.

Operator Magic Method
== __eq__
!= __ne__
< __lt__
<= __le__
> __gt__
>= __ge__

Mga Magic Method para sa Uri ng Container

Maaari kang gumawa ng mga klase na parang listahan o diksyunaryo ang galaw.

__len__: Pagkuha ng Bilang ng mga Elemento

Ang __len__ ay isang magic method na nagbabalik ng bilang ng mga elemento.

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__: Pag-access gamit ang Index

Ang __getitem__ method ay tinatawag kapag gumagamit ng index access.

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__ at __delitem__: Pagsusulat at Pagbubura

Ang __setitem__ at __delitem__ methods ay tinatawag kapag nagsusulat o nagbubura ng item.

 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']

Mga Magic Method para sa Iteration

Upang gawing iterable ang isang object sa for loop, ipatupad ang mga sumusunod:.

__iter__ at __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

Context Manager (with Statement)

Sa pamamagitan ng pagde-define ng __enter__ at __exit__, maaari kang magpatupad ng pre- at post-processing para sa with statement.

 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)

Callable na Object: __call__

Sa pagde-define ng __call__ method, magagawa mong matawag ang isang instance na parang isang function.

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!

Buod

Ang mga magic method sa Python ay makapangyarihang paraan upang magdagdag ng natural at madaling intindihing asal sa mga klase. Bawat method ay may malinaw na layunin, at ang tamang pagpapatupad nito ay nagbibigay-daan upang makapagsulat ka ng mas flexible at Pythonic na code.

Ang mga magic method ay nagsisilbing 'invisible interface' na sumusuporta kung paano nagkakaugnayan at kumikilos ang mga Python object sa likod ng eksena.

Maaari mong sundan ang artikulo sa itaas gamit ang Visual Studio Code sa aming YouTube channel. Paki-check din ang aming YouTube channel.

YouTube Video