Thuta Learning
Python
IntermediateProgrammingအခြေခံ

Magic Methods (Enhanced)

Pythonသင်ခန်းစာ 2530 မိနစ်

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • __repr__ နဲ့ __str__ ကို ခွဲခြားပြီး debug လုပ်ရလွယ်တဲ့ __repr__ ရေးနိုင်ဖို့
  • __add__ နဲ့ __eq__ ကို ရေးပြီး မထောက်ပံ့တဲ့ type အတွက် NotImplemented ပြန်ပေးနိုင်ဖို့
  • __eq__ နဲ့ __hash__ ကို ကိုက်ညီအောင် ထားရတဲ့ အကြောင်းရင်းကို ရှင်းပြနိုင်ဖို့
  • __len__, __getitem__, __iter__, __contains__ နဲ့ container လို အလုပ်လုပ်တဲ့ class ရေးနိုင်ဖို့

ရိုးရိုးလေး ရှင်းပြမယ်

ရိုးရိုးလေး ရှင်းရရင်

Python ရဲ့ syntax တွေ (+, ==, len(), print(), for) ကို ပလပ်ပေါက်တွေလို့ မြင်ကြည့်ပါ။ int, str, list လို built-in type တွေမှာ ပလပ်ခေါင်း အားလုံး ပါပြီးသားမို့ "a" + "b" တို့ len([1, 2]) တို့ အလုပ်လုပ်ပါတယ်။ ကိုယ်ရေးတဲ့ class အသစ်မှာတော့ ပလပ်ခေါင်း မရှိသေးလို့ v1 + v2 လို့ ရေးရင် TypeError တက်ပါတယ်။

Magic method (dunder method) တွေက အဲဒီ ပလပ်ခေါင်းတွေပါ။ __add__ ရေးလိုက်ရင် + အလုပ်လုပ်ပြီး __len__ ရေးလိုက်ရင် len() အလုပ်လုပ်ပါတယ်။ ဒီ method တွေကို ကိုယ်တိုင် တိုက်ရိုက် ခေါ်တာ မဟုတ်ပါဘူး၊ Python က သင့်တော်တဲ့ syntax ကို တွေ့တဲ့အခါ နောက်ကွယ်ကနေ ခေါ်ပေးတာပါ။

Problem → Why → Solution

ပြဿနာ: print လုပ်ရင် အသုံးမဝင်တဲ့ စာ၊ == က အမြဲ False

Magic method မပါတဲ့ Money class ကို ကြည့်ပါ။ print(price) လုပ်ရင် <__main__.Money object at 0x...> ဆိုတဲ့ memory address ပဲ ထွက်ပြီး log ထဲမှာ ဘာငွေပမာဏလဲ မသိရပါဘူး။ ပိုဆိုးတာက value တူတဲ့ Money object နှစ်ခုကို == နဲ့ နှိုင်းယှဉ်ရင် False ရပါတယ်၊ ဒါကြောင့် test တွေ မျက်စိလည်စရာ ကျရှုံးပါတယ်။

money_plain.py
class Money:
    def __init__(self, amount, currency):
        self.amount, self.currency = amount, currency

price = Money(5, "USD")
print(price)                         # <__main__.Money object at 0x...>
print(price == Money(5, "USD"))      # False

ဘာကြောင့် ဒီလို ဖြစ်တာလဲ

Class တိုင်းက object class ဆီကနေ default magic method တွေကို ဆက်ခံပါတယ်။ Default __repr__ က class နာမည်နဲ့ memory address ကိုပဲ ပြပြီး default __eq__ က "object တစ်ခုတည်း ဟုတ်မဟုတ်" (is) ကိုပဲ စစ်ပါတယ်။ Python က သင့် object ကို ဘယ်လို ပြရမလဲ၊ ဘယ်အချိန် တူတယ်လို့ သတ်မှတ်ရမလဲ မသိလို့ပါ။ __repr__ နဲ့ __eq__ ကို override လုပ်ပြီး အဲဒါကို ပြောပြရပါမယ်။

Core concept: Python data model ရဲ့ ချိတ်ဆက်ချက်များ

Python ရဲ့ "data model" က syntax တစ်ခုစီကို magic method တစ်ခုစီနဲ့ တွဲထားပါတယ်: len(x) က type(x).__len__(x) ကို၊ a + b က a.__add__(b) ကို၊ x in c က c.__contains__(x) ကို ခေါ်ပါတယ်။ Method နာမည်တွေ အရှေ့ရော အနောက်ပါ underscore နှစ်ခုစီ ပါလို့ "dunder" (double underscore) လို့ ခေါ်ကြပါတယ်။ ကိုယ်တိုင် dunder နာမည်အသစ် မတီထွင်ပါနဲ့၊ Python က သတ်မှတ်ထားတဲ့ နာမည်တွေကိုပဲ အဓိပ္ပာယ် ရှိပါတယ်။

__repr__ နဲ့ __str__ ကွာပါတယ်။ __repr__ က developer အတွက်ပါ — တိကျပြီး ဖြစ်နိုင်ရင် Vector(1, 2) လို object ကို ပြန်ဖန်တီးလို့ရတဲ့ code ပုံစံ ဖြစ်သင့်ပါတယ်။ List ထဲက object တွေ၊ debugger နဲ့ REPL က __repr__ ကို သုံးပါတယ်။ __str__ က အသုံးပြုသူ ဖတ်ဖို့ ဖြစ်ပြီး print() နဲ့ str() က သုံးပါတယ်။ __str__ မရေးထားရင် Python က __repr__ ကို အစားသုံးလို့ အနည်းဆုံး __repr__ ကိုတော့ အမြဲ ရေးထားပါ။

Operator method တွေမှာ အရေးကြီးတဲ့ စည်းမျဉ်း တစ်ခု ရှိပါတယ်: မထောက်ပံ့တဲ့ type ရောက်လာရင် error raise မလုပ်ဘဲ NotImplemented (special value) ကို return ပြန်ပါ။ အဲဒီအခါ Python က တခြားဘက် object ရဲ့ reflected method (ဥပမာ __radd__) ကို ကြိုးစားကြည့်ပြီး ဘယ်သူမှ မထောက်ပံ့မှ ရှင်းလင်းတဲ့ TypeError ကို ကိုယ်တိုင် raise လုပ်ပါတယ်။ == မှာဆိုရင်တော့ နောက်ဆုံး identity နှိုင်းယှဉ်မှုဆီ ပြန်သွားလို့ False ရပါတယ်။

__eq__ ကို ရေးလိုက်တာနဲ့ Python က __hash__ ကို None လုပ်လိုက်လို့ object ကို set ထဲ၊ dict key အဖြစ် မသုံးနိုင်တော့ပါဘူး။ ပြန်သုံးချင်ရင် __eq__ မှာ နှိုင်းယှဉ်တဲ့ field တွေနဲ့ပဲ __hash__ ကို ရေးရပါမယ် — a == b ဖြစ်ရင် hash(a) == hash(b) ဖြစ်ကို ဖြစ်ရပါမယ်။ Hash ထဲ ထည့်ပြီးမှ အဲဒီ field တွေကို မပြောင်းပါနဲ့။

Operator overloading ကို သဘာဝကျမှပဲ သုံးပါ — vector နှစ်ခု ပေါင်းတာ၊ ငွေနှစ်ခု ပေါင်းတာ အဓိပ္ပာယ်ရှိပေမယ့် user + order လို code က ဖတ်တဲ့သူကို အံ့အားသင့်စေပါတယ်။

မှတ်ထားရမယ့် ပုံစံ: syntax က dunder ကို ခေါ်တယ်
  1. Python က a + b ကို တွေ့
  2. a.__add__(b) ကို ခေါ်
  3. NotImplemented ဆိုရင် b.__radd__(a)
  4. နှစ်ခုလုံး မရရင် TypeError

len(), ==, in, for, print() တိုင်းမှာ ဒီလို ချိတ်ဆက်ထားတဲ့ dunder method တစ်ခုစီ ရှိပါတယ်။

အထွေထွေ ပုံစံ

python
class MyType:
    def __repr__(self):              # repr(obj), REPL, lists
        return f"MyType({self.field!r})"

    def __eq__(self, other):         # obj == other
        if not isinstance(other, MyType):
            return NotImplemented
        return self.field == other.field

    def __hash__(self):              # needed again once __eq__ exists
        return hash(self.field)

Magic method တစ်ခုစီက syntax တစ်ခုနဲ့ တွဲပါတယ်။ !r က value ရဲ့ repr() ကို သုံးလို့ string တွေမှာ quote ပါပါတယ်။ မသိတဲ့ type ဆိုရင် NotImplemented ပြန်ပြီး __hash__ ကို __eq__ နှိုင်းယှဉ်တဲ့ field တွေကနေ တွက်ပါ။

Example: Vector နဲ့ Bag

Vector က representation, arithmetic, equality နဲ့ hashing ကို ပြပြီး Bag က container protocol (len, indexing, iteration, in) ကို ပြပါတယ်။ v1 + 5 ကို ကြိုးစားတဲ့ line မှာ NotImplemented က ဘယ်လို TypeError ဖြစ်လာလဲ သတိထားကြည့်ပါ။

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

    def __repr__(self):                  # for developers: repr(v), lists
        return f"Vector({self.x}, {self.y})"

    def __str__(self):                   # for humans: print(v), str(v)
        return f"({self.x}, {self.y})"

    def __add__(self, other):            # v1 + v2
        if not isinstance(other, Vector):
            return NotImplemented        # let Python try other options
        return Vector(self.x + other.x, self.y + other.y)

    def __eq__(self, other):             # v1 == v2
        if not isinstance(other, Vector):
            return NotImplemented
        return (self.x, self.y) == (other.x, other.y)

    def __hash__(self):                  # keep hash consistent with ==
        return hash((self.x, self.y))


class Bag:
    def __init__(self, items):
        self._items = list(items)

    def __len__(self):                   # len(bag)
        return len(self._items)

    def __getitem__(self, index):        # bag[0]
        return self._items[index]

    def __iter__(self):                  # for item in bag
        return iter(self._items)

    def __contains__(self, item):        # "x" in bag
        return item in self._items


v1, v2 = Vector(1, 2), Vector(3, 4)
print(v1 + v2)
print([v1, v2])
print(v1 == Vector(1, 2), len({v1, Vector(1, 2)}))

try:
    v1 + 5
except TypeError as e:
    print("TypeError:", e)

bag = Bag(["pen", "book", "cup"])
print(len(bag), bag[0], "cup" in bag)
print([item.upper() for item in bag])

Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်

  1. Lines 43-44print([v1, v2])

    print(v1 + v2) က __str__ ကို သုံးလို့ (4, 6) ထွက်ပြီး list ကို print လုပ်တဲ့အခါ အထဲက element တွေအတွက် __repr__ ကို သုံးလို့ Vector(1, 2) ပုံစံ ထွက်ပါတယ်။

  2. Line 13return NotImplemented # let Python try other options

    5 က Vector မဟုတ်လို့ NotImplemented ပြန်ပါတယ်။ int ကလည်း Vector နဲ့ ပေါင်းနည်း မသိလို့ Python က "unsupported operand type(s)" TypeError ကို raise လုပ်ပါတယ်။

  3. Line 45print(v1 == Vector(1, 2), len({v1, Vector(1, 2)}))

    __eq__ ကြောင့် value တူရင် True ရပါတယ်။ __hash__ က == နဲ့ ကိုက်ညီလို့ set က object နှစ်ခုကို တစ်ခုတည်းလို့ မှတ်ပြီး length 1 ဖြစ်ပါတယ်။

  4. Line 53print(len(bag), bag[0], "cup" in bag)

    len() က __len__ ကို၊ bag[0] က __getitem__ ကို၊ in က __contains__ ကို ခေါ်ပါတယ်။

  5. Line 54print([item.upper() for item in bag])

    Comprehension ထဲက for က __iter__ ကို ခေါ်ပြီး iterator ကနေ item တစ်ခုချင်းစီ ယူပါတယ်။

You should see
(4, 6)
[Vector(1, 2), Vector(3, 4)]
True 1
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'
3 pen True
['PEN', 'BOOK', 'CUP']
CategoryMethods
Lifecycle__init__, __new__, __del__
Representation__repr__, __str__, __format__
Arithmetic__add__, __sub__, __mul__, __truediv__
Containers__len__, __getitem__, __iter__

Comparison method တွေနဲ့ sorted()

__lt__ (<), __le__ (<=), __gt__ (>), __ge__ (>=) တွေက ordering အတွက်ပါ။ sorted(), min(), max() တို့က __lt__ ကိုပဲ အဓိက သုံးလို့ __lt__ ရေးထားရုံနဲ့ list ကို sort လုပ်လို့ ရပါတယ်။ Comparison အားလုံး လိုချင်ရင် functools.total_ordering decorator က __eq__ နဲ့ __lt__ ကနေ ကျန်တာတွေကို ဖြည့်ပေးပါတယ်။ Data class ဖြစ်ရင်တော့ @dataclass(order=True) က အဲဒီ method အားလုံးကို field အစဉ်အတိုင်း ထုတ်ပေးပါတယ်။

Syntaxခေါ်တဲ့ method
a < ba.__lt__(b)
a - b, a * ba.__sub__(b), a.__mul__(b)
5 + a (a က ညာဘက်)a.__radd__(5)
bool(a), if a:a.__bool__(), မရှိရင် __len__
with a:a.__enter__(), a.__exit__(...)

လက်တွေ့ project တွေမှာ

Real project တွေမှာ ဘယ်လို သုံးလဲ

Library ကြီးတွေက magic method တွေကြောင့် "Python ရဲ့ built-in တစ်ခုလို" ခံစားရပါတယ်။ NumPy array တွေမှာ a + b က element တစ်ခုချင်းစီ ပေါင်းတာ __add__ ကြောင့်ပါ၊ pandas မှာ df["price"] က __getitem__ ကြောင့်ပါ၊ pathlib မှာ Path("data") / "file.csv" က __truediv__ ကြောင့်ပါ။ Django QuerySet တွေကို len(), slicing, for loop နဲ့ သုံးလို့ ရတာလည်း container method တွေကြောင့်ပါ။

ကိုယ်ပိုင် application code မှာလည်း __repr__ တစ်ခုတည်းက အချိန်အများကြီး သက်သာစေပါတယ်။ Error log ထဲမှာ <Order object at 0x7f...> အစား Order(id=1042, status='paid') လို့ ပေါ်ရင် ဘယ် order မှာ ပြဿနာ ဖြစ်လဲ ချက်ချင်း သိပါတယ်။ Money, Coordinate, DateRange လို value object တွေမှာ __eq__ နဲ့ __hash__ ရှိရင် set နဲ့ dict key အဖြစ် သုံးလို့ ရပြီး test တွေမှာ assert total == Money(10, "USD") လို ရိုးရှင်းတဲ့ စစ်ဆေးမှုတွေ ရေးလို့ ရပါတယ်။

အမှားများ

အဖြစ်များတဲ့ အမှားတွေ

1. __eq__ ရေးပြီး set ထဲ ထည့်လို့ မရတော့တာ

__eq__ ပဲ ရေးပြီး __hash__ မရေးရင် {Vector(1, 2)} က "TypeError: unhashable type: 'Vector'" ပေးပါတယ်။ Object က immutable လို သုံးမယ်ဆိုရင် __eq__ နဲ့ field တူတူနဲ့ __hash__ ရေးပါ၊ mutable ဖြစ်ရင်တော့ unhashable အတိုင်း ထားတာ မှန်ပါတယ်။

2. NotImplemented အစား False ဒါမှမဟုတ် error ပြန်တာ

__add__ ထဲမှာ type မကိုက်ရင် raise TypeError("bad") လုပ်လိုက်ရင် တခြား class ရဲ့ __radd__ ကို ကြိုးစားခွင့် မရတော့ပါဘူး။ __eq__ ထဲမှာ return False လုပ်ရင်လည်း တခြားဘက်က နှိုင်းယှဉ်နည်းကို ပိတ်လိုက်တာပါ။ NotImplemented ကို return ပြန်ပါ (raise NotImplementedError နဲ့ မရောပါနဲ့)။

3. __repr__ / __str__ က string မဟုတ်တာ ပြန်တာ

return self.amount လို number ပြန်ရင် print() က "TypeError: __str__ returned non-string" ပေးပါတယ်။ __len__ ကလည်း 0 နဲ့ အထက် integer ပဲ ပြန်ရပါမယ်။ Dunder method တိုင်းမှာ return type စည်းမျဉ်း ရှိပါတယ်။

Best Practices

အကောင်းဆုံး အလေ့အကျင့်များ

  • Class အသစ်တိုင်းမှာ __repr__ ကို ပထမဆုံး ရေးပါ၊ အချိန် အနည်းဆုံး ပေးရပြီး debug လုပ်တဲ့အခါ အကျိုးအများဆုံး ရပါတယ်။
  • Data သက်သက် သိမ်းတဲ့ class ဆိုရင် __init__, __repr__, __eq__ ကို လက်နဲ့ မရေးဘဲ @dataclass ကို သုံးပါ၊ immutable လိုရင် frozen=True ထည့်ပါ၊ ဒါဆို __hash__ ပါ ရပါတယ်။
  • Operator တစ်ခု overload လုပ်ရင် ဆက်စပ်နေတဲ့ operator တွေကိုလည်း ကိုက်ညီအောင် ထားပါ — a + b ရရင် a - b နဲ့ a += b ကလည်း မျှော်လင့်ထားတဲ့အတိုင်း ဖြစ်ရပါမယ်။
  • __len__ က အချိန်ကြာတဲ့ အလုပ် မလုပ်ပါစေနဲ့၊ if obj: တိုင်းမှာ ခေါ်ခံရနိုင်ပါတယ်။

Mini challenge

Mini challenge: Money value object

ပေါင်းလို့ရ၊ နှိုင်းယှဉ်လို့ရ၊ sort လုပ်လို့ရပြီး debug လုပ်ရလွယ်တဲ့ Money class ကို magic method တွေနဲ့ ရေးပါ။

  • __repr__ က Money(10, 'USD') ပုံစံ ပြန်ပေးရမယ်
  • __add__ က currency တူမှ ပေါင်းရမယ်၊ မတူရင် ValueError၊ Money မဟုတ်ရင် NotImplemented
  • __eq__ က amount နဲ့ currency နှစ်ခုလုံး တူမှ True ဖြစ်ရမယ်
  • __lt__ ရေးပြီး sorted() နဲ့ min() အလုပ်လုပ်တာ ပြရမယ်
money.py
class Money:
    def __init__(self, amount, currency):
        self.amount = amount
        self.currency = currency

    def __repr__(self):
        # TODO: return "Money(10, 'USD')" (hint: !r adds the quotes)
        pass

    # TODO: __add__ : NotImplemented for non-Money, ValueError for mixed currency

    # TODO: __eq__  : compare amount and currency

    # TODO: __lt__  : compare amounts of the same currency


# TODO: prices = three USD amounts; print a sum, sorted(prices) and min(prices)
# TODO: show that adding USD to EUR raises ValueError

ရလဒ်: Output က ဒီလို ထွက်ရပါမယ်: Money(10, 'USD') [Money(3, 'USD'), Money(5, 'USD'), Money(7, 'USD')] True Money(3, 'USD') error: cannot add different currencies

အရိပ်အမြွက် ကြည့်ရန်

f"Money({self.amount}, {self.currency!r})" က currency ကို quote နဲ့ ပြပါတယ်။ sorted() က __lt__ ကိုပဲ လိုလို့ __gt__ မရေးလည်း ရပါတယ်။

အဖြေ ကြည့်ရန်
money.py
class Money:
    def __init__(self, amount, currency):
        self.amount = amount
        self.currency = currency

    def __repr__(self):
        return f"Money({self.amount}, {self.currency!r})"

    def __add__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        if other.currency != self.currency:
            raise ValueError("cannot add different currencies")
        return Money(self.amount + other.amount, self.currency)

    def __eq__(self, other):
        if not isinstance(other, Money):
            return NotImplemented
        return (self.amount, self.currency) == (other.amount, other.currency)

    def __lt__(self, other):
        if not isinstance(other, Money) or other.currency != self.currency:
            return NotImplemented
        return self.amount < other.amount

    __hash__ = None          # Python does this anyway once __eq__ exists


prices = [Money(7, "USD"), Money(3, "USD"), Money(5, "USD")]
print(prices[0] + prices[1])
print(sorted(prices))
print(Money(3, "USD") == prices[1], min(prices))
try:
    Money(1, "USD") + Money(1, "EUR")
except ValueError as e:
    print("error:", e)

Quick Quiz 1 / 3

Class မှာ __repr__ ("R" ပြန်) နဲ့ __str__ ("S" ပြန်) နှစ်ခုလုံး ရှိတယ်။ print([obj]) က ဘာထုတ်မလဲ။

Quick Quiz 2 / 3

Point class မှာ __eq__ ရေးထားပြီး __hash__ မရေးထားဘူး။ {Point(1, 2)} က ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Vector.__add__ မှာ other က Vector မဟုတ်ရင် ဘာလုပ်သင့်လဲ။

မှတ်ထားရမယ့် အချက်များ

  • Magic method တွေက +, ==, len(), in, for, print() လို syntax ကို ကိုယ်ပိုင် class နဲ့ ချိတ်ပေးပါတယ်။
  • __repr__ က developer အတွက်၊ __str__ က user အတွက်ဖြစ်ပြီး အနည်းဆုံး __repr__ ကို အမြဲ ရေးပါ။
  • Operator method တွေက မထောက်ပံ့တဲ့ type အတွက် NotImplemented ကို return ပြန်ရပါမယ်။
  • __eq__ ရေးရင် __hash__ ကို field တူတူနဲ့ ရေးပါ၊ ဒါမှမဟုတ် unhashable အတိုင်း ထားပါ။

Python Documentation — Classes — Python Software Foundation

နောက်ဆုံးပြင်ဆင်ရက်

Progress ကို ဤ browser (ဤစက်) တွင်သာ သိမ်းထားပါသည်။ အခြားစက်များနှင့် sync မလုပ်ပါ။

ဤသင်ခန်းစာတွင် အမှားတွေ့ပါက အကြောင်းကြားရန်သင့် email app ကို ဤသင်ခန်းစာလိပ်စာ ဖြည့်ပြီးသားဖြင့် ဖွင့်ပေးပါမည် — သင်ကိုယ်တိုင် ပို့မှသာ ပို့မည်ဖြစ်သည်။

Magic Methods (Enhanced) | Thuta Learning