Thuta Learning
Python
IntermediateProgrammingအခြေခံ

Polymorphism (Enhanced)

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

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

  • if/elif isinstance() chain တစ်ခုကို method ခေါ်ရုံ code နဲ့ အစားထိုးနိုင်ဖို့
  • Duck typing ဆိုတာ ဘာလဲ၊ inheritance မပါဘဲ ဘာကြောင့် အလုပ်လုပ်လဲ ရှင်းပြနိုင်ဖို့
  • len() နဲ့ + လို built-in တွေက polymorphic ဖြစ်ပုံကို ဥပမာပေးနိုင်ဖို့
  • abc.ABC + @abstractmethod ဒါမှမဟုတ် typing.Protocol နဲ့ လိုအပ်တဲ့ interface ကို ဖော်ပြနိုင်ဖို့

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

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

Remote control က "Power" ခလုတ်ကို နှိပ်လိုက်ရင် TV ဆိုရင် TV ပွင့်ပြီး air-con ဆိုရင် air-con ပွင့်ပါတယ်။ ခလုတ်တစ်ခုတည်း၊ command တစ်ခုတည်း ဖြစ်ပေမယ့် စက်တစ်လုံးချင်းစီက ကိုယ့်နည်းကိုယ့်ဟန်နဲ့ တုံ့ပြန်ပါတယ်။ Polymorphism ("ပုံစံအမျိုးမျိုး") ဆိုတာ ဒါပါပဲ။

Code မှာဆိုရင် shape.area() လို့ ခေါ်လိုက်တာနဲ့ Circle က πr² နဲ့ တွက်ပြီး Rectangle က အလျား × အနံ နဲ့ တွက်ပါတယ်။ ခေါ်တဲ့သူက shape ဘယ်အမျိုးအစားလဲ သိစရာ မလိုပါဘူး၊ "area() ရှိရင် ရပြီ" ဆိုတာပဲ သိဖို့ လိုပါတယ်။

Problem → Why → Solution

ပြဿနာ: type အသစ်တိုင်း if/elif ထပ်ထည့်ရတယ်

Polymorphism မသုံးခင် ဧရိယာ စုစုပေါင်း တွက်တဲ့ function ကို ဒီလို type စစ်ပြီး ရေးကြပါတယ်။ Triangle class အသစ် ထည့်လိုက်တဲ့နေ့မှာ total_area() ကို ပြင်ဖို့ မေ့သွားရင် triangle တွေကို အသံတိတ် ကျော်သွားပြီး ရလဒ်က မှားနေပါလိမ့်မယ်။ Project ထဲမှာ ဒီလို type စစ်တဲ့ function ဆယ်ခု ရှိရင် shape အသစ်တစ်ခု ထည့်တိုင်း နေရာဆယ်ခု ပြင်ရပါတယ်။

areas_by_type.py
def total_area(shapes):
    total = 0
    for s in shapes:
        if isinstance(s, Circle):
            total += 3.14159 * s.radius ** 2
        elif isinstance(s, Rectangle):
            total += s.width * s.height
        # Triangle was added later... and silently ignored here
    return total

ဘာကြောင့် ဒီ design က ကျိုးလွယ်တာလဲ

Shape တစ်ခုချင်းစီရဲ့ ဧရိယာ တွက်နည်းက shape class တွေ အပြင်ဘက်မှာ ရှိနေလို့ပါ။ Class အသစ်ကို ရေးတဲ့သူက ဒီ function ရှိမှန်း မသိနိုင်ပါဘူး။ တွက်နည်းကို class တစ်ခုချင်းစီရဲ့ area() method ထဲ ရွှေ့လိုက်ရင် total_area() က s.area() ကို ခေါ်ရုံပဲ လိုပြီး shape အသစ်ထည့်တိုင်း ဒီ function ကို ပြင်စရာ မလိုတော့ပါဘူး။

Core concept: ခေါ်တဲ့ operation တစ်ခု၊ implementation အမျိုးမျိုး

Polymorphism ရဲ့ အဓိကက caller ဘက်မှာ operation တစ်ခုတည်းကို ခေါ်ပြီး ဘယ် code run မလဲဆိုတာကို object ကိုယ်တိုင် ဆုံးဖြတ်ခွင့် ပေးတာပါ။ shape.area() ကို ခေါ်တဲ့အခါ Python က shape ရဲ့ class ကနေ area ကို runtime မှာ ရှာပါတယ်၊ ဒါကြောင့် list ထဲမှာ Circle ပါရင် Circle.area() ကို၊ Rectangle ပါရင် Rectangle.area() ကို ခေါ်ပါတယ်။ Python ရဲ့ polymorphism ပုံစံ သုံးမျိုးကို ကြည့်ရအောင်။

1. Inheritance + overriding

Parent class (Shape) က area() ဆိုတဲ့ method နာမည်ကို သတ်မှတ်ပြီး child class တွေက override လုပ်ပါတယ်။ Parent ထဲက describe() လို method က self.area() ကို ခေါ်ရင် child တစ်ခုချင်းစီရဲ့ version ကို ရပါတယ်။

2. Duck typing

"ဘဲလို လမ်းလျှောက်ပြီး ဘဲလို အော်ရင် ဘဲပဲ" ဆိုတဲ့ စကားကနေ လာတာပါ။ Python က object ရဲ့ type ကို မစစ်ဘဲ method ရှိမရှိကိုပဲ ကြည့်ပါတယ်။ Example ထဲက Plot class က Shape ကို မဆက်ခံပေမယ့် area() ရှိလို့ total_area() ထဲ ထည့်လို့ ရပါတယ်။ Method မရှိတဲ့ object ကို ပို့ရင်တော့ ခေါ်တဲ့ အချိန်ကျမှ AttributeError တက်ပါတယ်။

3. Built-in နဲ့ operator polymorphism

len() က string, list, dict အားလုံးနဲ့ အလုပ်လုပ်ပြီး + က number တွေကို ပေါင်း၊ string နဲ့ list တွေကို ဆက်ပါတယ်။ နောက်ကွယ်မှာ len(x) က x.__len__() ကို ခေါ်ပြီး a + b က a.__add__(b) ကို ခေါ်တာပါ — magic method lesson မှာ ကိုယ်ပိုင် class တွေကို ဒီလို ပေါင်းစပ်နည်း ကြည့်ပါမယ်။

Duck typing က ပြောင်းလွယ်ပေမယ့် "ဘယ် method တွေ လိုလဲ" ဆိုတာ code ထဲမှာ ရေးထားတာ မရှိပါဘူး။ abc module ရဲ့ ABC နဲ့ @abstractmethod က child class တစ်ခုက လိုအပ်တဲ့ method ကို မရေးရင် object ဖန်တီးတဲ့ အချိန်မှာပဲ TypeError ပေးပါတယ်။ typing.Protocol ကတော့ inheritance မလိုဘဲ "area() -> float ရှိတဲ့ ဘယ် object မဆို" လို့ type checker အတွက် ဖော်ပြပါတယ်။ အရေးကြီးတာက caller ဘက်မှာ type အလိုက် ခွဲမရေးတော့ဘဲ common operation တစ်ခုကို ခေါ်တာပါ၊ ဒါမှ type အသစ်ထည့်တိုင်း ရှိပြီးသား code ကို မပြင်ရတော့မှာပါ။

မှတ်ထားရမယ့် ပုံစံ: object က ဆုံးဖြတ်တယ်
  1. Caller က thing.area() ကို ခေါ်
  2. Python က thing ရဲ့ class မှာ area ရှာ
  3. အဲဒီ class ရဲ့ code run
  4. Caller က type ကို ဘယ်တော့မှ မစစ်

Type အသစ် ထည့်ချင်ရင် method ပါတဲ့ class အသစ် ရေးရုံပါ၊ caller ကို မပြင်ရပါဘူး။

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

python
class KindA:
    def operation(self):
        return "A's way"

class KindB:
    def operation(self):
        return "B's way"

def use_all(items):
    for item in items:
        item.operation()          # no isinstance() checks

Class တွေက method နာမည်နဲ့ parameter တူတူ ရှိရုံပါပဲ၊ common parent ရှိရင်လည်း ရ၊ မရှိရင်လည်း ရပါတယ်။ Caller က method ကို ခေါ်ရုံပဲ လုပ်ပြီး type အလိုက် ခွဲမရေးပါဘူး။

Example: shape တွေနဲ့ ဧရိယာ စုစုပေါင်း

Circle နဲ့ Rectangle က Shape ကို ဆက်ခံပြီး area() ကို override လုပ်ပါတယ်။ Plot (မြေကွက်) ကတော့ Shape နဲ့ မဆိုင်ပေမယ့် area() ရှိလို့ total_area() က လက်ခံပါတယ်။ နောက်ဆုံး line နှစ်ကြောင်းက built-in polymorphism ကို ပြပါတယ်။

shapes.py
import math


class Shape:
    def area(self):
        raise NotImplementedError("subclasses must implement area()")

    def describe(self):
        return f"{type(self).__name__} with area {self.area():.2f}"


class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return math.pi * self.radius ** 2


class Rectangle(Shape):
    def __init__(self, width, height):
        self.width, self.height = width, height

    def area(self):
        return self.width * self.height


class Plot:                      # NOT a Shape, but it has area()
    def __init__(self, acres):
        self.acres = acres

    def area(self):
        return self.acres * 4046.86


def total_area(things):
    return sum(thing.area() for thing in things)   # no type checks


shapes = [Circle(1), Rectangle(3, 4)]
for shape in shapes:
    print(shape.describe())

print(round(total_area(shapes + [Plot(0.5)]), 2))

# Built-in polymorphism: one operation, many types
print(len("Sai"), len([1, 2, 3, 4]), len({"a": 1, "b": 2}))
print(2 + 3, "py" + "thon", [1] + [2])

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

  1. Line 6raise NotImplementedError("subclasses must implement area()")

    Shape ကိုယ်တိုင်က ဧရိယာ မတွက်တတ်ပါဘူး။ Child class က override မလုပ်ရင် ခေါ်တဲ့အချိန်မှာ ရှင်းလင်းတဲ့ error ပေါ်အောင် ထားတာပါ။

  2. Line 9return f"{type(self).__name__} with area {self.area():.2f}"

    describe() ကို Shape ထဲမှာ တစ်ကြိမ်ပဲ ရေးထားပေမယ့် self.area() က child တစ်ခုချင်းစီရဲ့ version ကို ခေါ်ပါတယ်။ :.2f က ဒသမ နှစ်နေရာ format လုပ်ပါတယ်။

  3. Line 28class Plot: # NOT a Shape, but it has area()

    Duck typing ပါ: Plot က Shape ကို မဆက်ခံပါဘူး။ total_area() က area() ကိုပဲ ခေါ်လို့ Plot ကို လက်ခံပါတယ်။

  4. Line 37return sum(thing.area() for thing in things) # no type checks

    isinstance() တစ်ခုမှ မပါပါဘူး။ π + 12 + 0.5 × 4046.86 = 2038.57 ရပါတယ်။ Shape အသစ်ထည့်လည်း ဒီ line ကို ပြင်စရာ မလိုပါဘူး။

  5. Lines 47-48print(2 + 3, "py" + "thon", [1] + [2])

    Operator တစ်ခုတည်းက type ပေါ်မူတည်ပြီး ပေါင်းတာ (5)၊ string ဆက်တာ (python)၊ list ဆက်တာ ([1, 2]) လုပ်ပါတယ်။

You should see
Circle with area 3.14
Rectangle with area 12.00
2038.57
3 4 2
5 python [1, 2]

ABC နဲ့ Protocol နဲ့ interface ကို ဖော်ပြခြင်း

NotImplementedError က method ကို ခေါ်မှ ပြဿနာ ပေါ်ပါတယ်။ ABC နဲ့ဆိုရင် အစောပိုင်း object ဖန်တီးတဲ့ အချိန်မှာပဲ ဖမ်းပေးပါတယ်။ အောက်က Square က area() ရေးဖို့ မေ့ထားလို့ Square(2) ကို ခေါ်တာနဲ့ TypeError တက်ပါတယ်။

abstract_shape.py
from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self): ...

class Square(Shape):
    def __init__(self, side):
        self.side = side
    # forgot to write area()

try:
    Square(2)
except TypeError as e:
    print(e)

typing.Protocol ကတော့ inheritance မလိုပါဘူး။ Field class က HasArea ကို နာမည်တောင် မသိပေမယ့် area() -> float ရှိလို့ mypy လို type checker က report() ထဲ ပို့တာကို လက်ခံပါတယ်။ Runtime မှာတော့ Protocol က ဘာမှ ထပ်မစစ်ပါဘူး။

protocol_shape.py
from typing import Protocol

class HasArea(Protocol):
    def area(self) -> float: ...

class Field:                      # never mentions HasArea
    def area(self) -> float:
        return 120.0

def report(item: HasArea) -> str:
    return f"area = {item.area()}"

print(report(Field()))

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

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

Python ရဲ့ "file-like object" က duck typing ရဲ့ နာမည်ကြီး ဥပမာပါ။ json.dump(data, f) က f ဟာ disk file လား၊ io.StringIO လား၊ network socket wrapper လား မစစ်ဘဲ f.write() ကိုပဲ ခေါ်ပါတယ်။ ဒါကြောင့် test ရေးတဲ့အခါ တကယ့် file အစား StringIO ကို ပို့ပြီး output ကို memory ထဲမှာ စစ်လို့ ရပါတယ်။

Payment system တွေမှာ CardPayment, WalletPayment, BankTransfer class တွေ အားလုံးက charge(amount) method ရှိပြီး checkout code က payment.charge(total) လို့ပဲ ခေါ်ပါတယ်။ Payment နည်းလမ်း အသစ် ထည့်တဲ့အခါ class အသစ်တစ်ခု ရေးရုံပါ။ Notification, export format (CSV, JSON, PDF), storage backend (local disk, S3) တွေမှာလည်း ဒီ pattern ကိုပဲ တွေ့ရပါတယ်။ Django ORM, Python logging handler လို library တွေကလည်း ကိုယ်ပိုင် class ကို သတ်မှတ်ထားတဲ့ method တွေနဲ့ ရေးပေးရုံနဲ့ framework ထဲ ချိတ်ဆက်လို့ ရအောင် ဒီနည်းကို သုံးပါတယ်။

အမှားများ

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

1. Override လုပ်ပြီးမှ type ကို ပြန်စစ်တာ

Class တွေမှာ area() ရှိပြီးသားဖြစ်ပေမယ့် caller ထဲမှာ if type(s) == Circle: လို ပြန်စစ်နေရင် polymorphism ရဲ့ အကျိုးကျေးဇူး ပျောက်သွားပါတယ်။ type() == က subclass တွေကိုလည်း လက်မခံလို့ ပိုဆိုးပါတယ်။ Type အလိုက် ကွာတဲ့ အလုပ်ကို method ထဲ ရွှေ့ပါ။

2. Method signature မတူအောင် ရေးတာ

Circle.area(self) ပေမယ့် Rectangle.area(self, unit) လို့ ရေးရင် total_area() က thing.area() ခေါ်တဲ့အခါ Rectangle မှာ "missing 1 required positional argument: 'unit'" TypeError တက်ပါတယ်။ Polymorphic method တွေက parameter တွေ တူရပါမယ်၊ ထပ်လိုတာ ရှိရင် default value ပေးပါ။

3. Return type မတူအောင် ပြန်ပေးတာ

class တစ်ခုက area() မှာ number ပြန်ပြီး နောက်တစ်ခုက "12 m²" လို string ပြန်ရင် sum() က TypeError ပေးပါတယ်။ Method နာမည်တူရုံနဲ့ မလုံလောက်ပါဘူး၊ ရလဒ်ရဲ့ အဓိပ္ပာယ်နဲ့ type လည်း တူရပါမယ်။

Best Practices

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

  • Polymorphic method တွေကို နာမည်၊ parameter နဲ့ return type တူအောင် ထားပြီး docstring တစ်နေရာမှာ "ဒီ method က ဘာ ပြန်ပေးရမလဲ" ကို ရေးထားပါ။
  • Class တွေကို သင်ကိုယ်တိုင် ထိန်းချုပ်ပြီး implement မလုပ်မိတာကို စောစော ဖမ်းချင်ရင် ABC ကို၊ third-party class တွေကိုပါ လက်ခံချင်ရင် Protocol ကို ရွေးပါ။
  • Type အလိုက် ခွဲတဲ့ if/elif တစ်ခုကို နေရာနှစ်ခုထက် ပိုမြင်လာရင် method တစ်ခုအဖြစ် class တွေထဲ ရွှေ့ဖို့ အချိန်ရောက်ပါပြီ။
  • Duck typing ကို ယုံပါ၊ ဒါပေမယ့် library ရဲ့ public boundary မှာ method မရှိတဲ့ object ဝင်လာရင် ရှင်းလင်းတဲ့ error message ပေးပါ။

Mini challenge

Mini challenge: notification channel များ

send(message) method ရှိတဲ့ sender class သုံးခု ရေးပြီး type မစစ်ဘဲ အားလုံးကို ခေါ်တဲ့ notify_all() function ရေးပါ။

  • EmailSender(address) နဲ့ SmsSender(phone) က string တစ်ခု return ပြန်ရမယ်
  • SmsSender က message 20 လုံးထက် ရှည်ရင် ပထမ 17 လုံး + "..." ပဲ ပို့ရမယ်
  • LogSender က common parent မရှိဘဲ duck typing နဲ့ အလုပ်လုပ်ရမယ်
  • notify_all(senders, message) ထဲမှာ isinstance() မပါရ
notify.py
class EmailSender:
    def __init__(self, address):
        self.address = address

    def send(self, message):
        # TODO: return "email to <address>: <message>"
        pass


class SmsSender:
    # TODO: __init__(self, phone) and send(self, message)
    # TODO: shorten messages longer than 20 characters
    pass


# TODO: LogSender with send(self, message) -> "log: <message>"


def notify_all(senders, message):
    # TODO: print what every sender returns, without isinstance()
    pass

ရလဒ်: notify_all(channels, "Your order has shipped") ရဲ့ output: email to aye@example.com: Your order has shipped sms to 09-555: Your order has sh... log: Your order has shipped

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

message[:17] + "..." က ပထမ စာလုံး 17 လုံးကို ယူပြီး "..." ဆက်ပါတယ်။ notify_all() ထဲမှာ for loop နဲ့ print(sender.send(message)) ပဲ လိုပါတယ်။

အဖြေ ကြည့်ရန်
notify.py
class EmailSender:
    def __init__(self, address):
        self.address = address

    def send(self, message):
        return f"email to {self.address}: {message}"


class SmsSender:
    def __init__(self, phone):
        self.phone = phone

    def send(self, message):
        short = message if len(message) <= 20 else message[:17] + "..."
        return f"sms to {self.phone}: {short}"


class LogSender:
    def send(self, message):
        return f"log: {message}"


def notify_all(senders, message):
    for sender in senders:
        print(sender.send(message))


channels = [EmailSender("aye@example.com"), SmsSender("09-555"), LogSender()]
notify_all(channels, "Your order has shipped")

Quick Quiz 1 / 3

class A: def go(self): return "A" ၊ class B: def go(self): return "B" (common parent မရှိ) ဆိုရင် print([x.go() for x in [A(), B(), A()]]) က ဘာထုတ်မလဲ။

Quick Quiz 2 / 3

from abc import ABC, abstractmethod ကို သုံးပြီး Shape(ABC) မှာ @abstractmethod area() ရှိတယ်။ area() မရေးထားတဲ့ class Blob(Shape) ကို Blob() လို့ ခေါ်ရင် ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Report export function မှာ if fmt == "csv": ... elif fmt == "json": ... ဆိုတဲ့ chain က ကြီးလာနေတယ်။ Polymorphism နဲ့ ဘယ်လို ပြင်မလဲ။

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

  • Polymorphism က caller ကို operation တစ်ခုတည်း ခေါ်စေပြီး ဘယ် code run မလဲကို object က ဆုံးဖြတ်ပါတယ်။
  • Python မှာ overriding, duck typing နဲ့ len(), + လို built-in polymorphism တွေ ရှိပါတယ်။
  • if/elif isinstance() chain တွေကို class တစ်ခုစီရဲ့ method နဲ့ အစားထိုးပါ။
  • လိုအပ်တဲ့ interface ကို ABC + @abstractmethod ဒါမှမဟုတ် typing.Protocol နဲ့ ဖော်ပြပါ။

Python Documentation — Classes — Python Software Foundation

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

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

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

Polymorphism (Enhanced) | Thuta Learning