Thuta Learning
Python
IntermediateProgrammingအခြေခံ

Inheritance (Enhanced)

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

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

  • class Child(Parent): နဲ့ child class ရေးပြီး method တစ်ခုကို override လုပ်နိုင်ဖို့
  • super().__init__() နဲ့ super().method() ကို သုံးပြီး parent ရဲ့ အလုပ်ကို ပြန်သုံးနိုင်ဖို့
  • isinstance(), issubclass() နဲ့ __mro__ ကို သုံးပြီး class hierarchy ကို စစ်နိုင်ဖို့
  • "is-a" ဆက်ဆံရေး မဟုတ်ရင် inheritance အစား composition ကို ရွေးနိုင်ဖို့

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

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

မိဘဆီကနေ မျက်လုံးအရောင်၊ ဆံပင်အရောင် ဆက်ခံရသလို child class ကလည်း parent class ဆီကနေ attribute နဲ့ method တွေကို အလိုအလျောက် ဆက်ခံပါတယ်။ Dog class ကို class Dog(Animal): လို့ ရေးလိုက်တာနဲ့ Animal မှာ ရေးထားတဲ့ __init__ နဲ့ method အားလုံးကို Dog object တွေက သုံးလို့ ရသွားပါတယ်။

ကွာခြားတဲ့ အပိုင်းကိုပဲ child class ထဲမှာ ပြန်ရေးရပါတယ်။ ခွေးက "Woof" လို့ ဟောင်ပြီး ကြောင်က "Meow" လို့ အော်သလို Dog နဲ့ Cat က speak() ကို ကိုယ်ပိုင်ပုံစံနဲ့ override လုပ်ပြီး နာမည်သိမ်းတာလို တူညီတဲ့ အလုပ်ကိုတော့ Animal ဆီမှာပဲ တစ်ကြိမ် ရေးထားပါတယ်။

Problem → Why → Solution

ပြဿနာ: copy-paste လုပ်ထားတဲ့ class တွေ

Inheritance မသုံးခင် Dog နဲ့ Cat class တွေကို ဒီလို copy-paste လုပ်ပြီး ရေးထားတယ် ဆိုပါစို့။ နာမည်ကို စာလုံးအကြီးနဲ့ စဖို့ title() ထည့်တဲ့ bug fix ကို Dog မှာ လုပ်ခဲ့ပေမယ့် Cat မှာ မေ့သွားပါတယ်။ Class နှစ်ခုက တစ်ချိန်က အတူတူ ဖြစ်ခဲ့ပေမယ့် အခုတော့ တစ်ခုနဲ့တစ်ခု မတူတော့ပါဘူး၊ Parrot, Rabbit ထပ်ထည့်လေ ဒီပြဿနာ ပိုကြီးလေပါပဲ။

pets_copy_paste.py
class Dog:
    def __init__(self, name):
        self.name = name.title()      # bug fix applied here...

    def describe(self):
        return f"{self.name} is a pet."

class Cat:
    def __init__(self, name):
        self.name = name              # ...but forgotten here

    def describe(self):
        return f"{self.name} is a pet."

print(Cat("kitty").describe())        # kitty is a pet.  (not capitalised)

ဘာကြောင့် ဒါက ပြဿနာလဲ

တူညီတဲ့ logic တွေ နေရာနှစ်ခုမှာ ရှိနေရင် ပြင်တဲ့အခါတိုင်း နှစ်နေရာလုံးကို မှတ်မိနေရပါတယ်၊ လူတွေက မှတ်မိဖို့ အမြဲ မေ့တတ်ပါတယ်။ Inheritance သုံးရင် __init__ နဲ့ describe() ကို Animal parent ထဲမှာ တစ်ကြိမ်ပဲ ရေးပြီး Dog နဲ့ Cat က ဆက်ခံပါတယ်၊ ဒါကြောင့် fix တစ်ခုက child class အားလုံးဆီ တစ်ပြိုင်နက် ရောက်ပါတယ်။

Core concept: override, super() နဲ့ MRO

class Dog(Animal): လို့ ရေးရင် Animal က parent (base class) ဖြစ်ပြီး Dog က child (subclass) ဖြစ်ပါတယ်။ Dog object ပေါ်မှာ method တစ်ခုကို ခေါ်တဲ့အခါ Python က Dog class ထဲမှာ အရင်ရှာပြီး မတွေ့ရင် Animal ထဲ ဆက်ရှာပါတယ်၊ နောက်ဆုံး object class အထိ ရှာပါတယ်။ Child class ထဲမှာ parent နဲ့ နာမည်တူ method ရေးလိုက်ရင် အဲဒီ method ကို အရင်တွေ့လို့ parent version ကို ဖုံးသွားပါတယ် — ဒါကို overriding လို့ ခေါ်ပါတယ်။

ဒီ lookup ကြောင့် parent ထဲက method တစ်ခုက child ရဲ့ method ကို ခေါ်နိုင်ပါတယ်။ Example မှာ Animal.introduce() က self.speak() ကို ခေါ်ပါတယ်၊ self က Dog object ဆိုရင် Dog.speak() ကို ရပါတယ်။ Parent က အလုပ်ရဲ့ ပုံစံကြမ်းကို သတ်မှတ်ပြီး child က အသေးစိတ် အပိုင်းကို ဖြည့်ပေးတာပါ။

Override လုပ်တဲ့အခါ parent ရဲ့ အလုပ်ကို လုံးဝ အစားထိုးချင်တာ မဟုတ်ဘဲ ထပ်ဖြည့်ချင်တာ များပါတယ်။ super() က အဲဒီအတွက်ပါ — super().__init__(name) က parent ရဲ့ __init__ ကို run ပြီး self.name ကို သတ်မှတ်ပေးပါတယ်။ Child မှာ __init__ ရေးပြီး super().__init__() ခေါ်ဖို့ မေ့ရင် parent ရဲ့ attribute တွေ ဘယ်တော့မှ မဖန်တီးမိဘဲ နောက်မှ AttributeError တက်ပါတယ်။

တိတိကျကျ ပြောရရင် super() က "parent" ကို ခေါ်တာ မဟုတ်ဘဲ MRO (method resolution order) ထဲက နောက်တစ်ဆင့်ကို ခေါ်တာပါ။ Class.__mro__ က Python ရှာမယ့် အစဉ်ကို tuple အဖြစ် ပြပါတယ် — Dog အတွက် Dog, Animal, object ပါ။ Parent တစ်ခုတည်း ရှိရင် နှစ်ခုက အတူတူပါပဲ၊ multiple inheritance မှာတော့ ဒီ အစဉ်က ဘယ် method အနိုင်ရလဲ ဆုံးဖြတ်ပါတယ်။

Inheritance ကို "is-a" ဆက်ဆံရေး တကယ်ရှိမှ သုံးပါ — Dog is an Animal ဆိုတာ မှန်ပါတယ်။ Car is an Engine ဆိုတာ မမှန်ပါဘူး၊ Car has an Engine ပါ၊ အဲဒီလို "has-a" ဆက်ဆံရေးအတွက် object တစ်ခုကို attribute အဖြစ် ထည့်တဲ့ composition ကို သုံးပါတယ်။ စစ်ဆေးနည်း လွယ်လွယ်လေး တစ်ခုရှိပါတယ်: parent ရဲ့ public method တိုင်းက child အတွက်လည်း အဓိပ္ပာယ်ရှိရင် inheritance က သင့်တော်ပါတယ်၊ တချို့ method တွေကို ဖုံးထားရမယ်၊ ပိတ်ထားရမယ် ဆိုရင်တော့ မသင့်တော်ပါဘူး။

မှတ်ထားရမယ့် ပုံစံ: အောက်ကနေ အပေါ် ရှာတယ်
  1. obj.method() ခေါ်
  2. obj ရဲ့ class ထဲ အရင်ရှာ
  3. မတွေ့ရင် MRO အစဉ်အတိုင်း parent ဆီ
  4. super() က MRO ရဲ့ နောက်တစ်ဆင့်ကို ခေါ်

Child မှာ ရှိတဲ့ method က အနိုင်ရပြီး super() နဲ့ parent version ကို ဆက်ခေါ်လို့ ရပါတယ်။

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

python
class Parent:
    def __init__(self, shared):
        self.shared = shared
    def action(self):
        return "parent behaviour"

class Child(Parent):
    def __init__(self, shared, extra):
        super().__init__(shared)       # parent sets self.shared
        self.extra = extra
    def action(self):                  # override
        return super().action() + " plus more"

class Child(Parent): က ဆက်ခံမှုကို ကြေညာပါတယ်။ Child မှာ __init__ ရေးရင် super().__init__(...) ကို ခေါ်ပြီးမှ ကိုယ်ပိုင် attribute တွေ ထည့်ပါ။ Override လုပ်တဲ့ method ထဲမှာ super().action() နဲ့ parent version ကို ပြန်သုံးနိုင်ပါတယ်။

Example: Animal, Dog နဲ့ Bird

Dog က speak() ကို လုံးဝ အစားထိုးပြီး Bird ကတော့ super() နဲ့ parent ရဲ့ __init__ နဲ့ speak() ကို ပြန်သုံးပြီး ထပ်ဖြည့်ပါတယ်။ introduce() ကို Animal ထဲမှာပဲ ရေးထားပေမယ့် child တစ်ခုချင်းစီရဲ့ speak() ကို ခေါ်တာကို ကြည့်ပါ။ နောက်ဆုံး line သုံးကြောင်းကတော့ hierarchy ကို ခန့်မှန်းမနေဘဲ တိုက်ရိုက် စစ်ကြည့်တာပါ။

animals.py
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return f"{self.name} makes a sound."

    def introduce(self):
        return f"I am {self.name}. {self.speak()}"


class Dog(Animal):
    def speak(self):                     # override the parent's method
        return f"{self.name} says Woof!"


class Bird(Animal):
    def __init__(self, name, can_fly=True):
        super().__init__(name)           # let Animal set self.name
        self.can_fly = can_fly

    def speak(self):
        base = super().speak()           # reuse, then extend
        return base + (" It flies away." if self.can_fly else " It waddles.")


rex = Dog("Rex")
penguin = Bird("Pingu", can_fly=False)

print(rex.introduce())
print(penguin.introduce())
print(isinstance(rex, Animal), isinstance(rex, Bird))
print(issubclass(Bird, Animal))
print([cls.__name__ for cls in Dog.__mro__])

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

  1. Line 9return f"I am {self.name}. {self.speak()}"

    Animal ထဲမှာ ရေးထားပေမယ့် self.speak() က self ရဲ့ class ကနေ စရှာလို့ Dog object အတွက် Dog.speak() ကို ခေါ်ပါတယ်။

  2. Line 12class Dog(Animal):

    Dog က Animal ကို ဆက်ခံလို့ __init__ မရေးရပါဘူး၊ Dog("Rex") က Animal.__init__ ကို သုံးပါတယ်။

  3. Line 19super().__init__(name)

    Bird မှာ ကိုယ်ပိုင် __init__ ရှိလို့ Animal.__init__ က အလိုအလျောက် မ run တော့ပါဘူး။ ဒီ line က self.name ကို သတ်မှတ်ဖို့ parent ကို ခေါ်ပါတယ်။

  4. Line 23base = super().speak()

    Parent ရဲ့ "Pingu makes a sound." ကို ယူပြီး can_fly ပေါ်မူတည်ပြီး စာကြောင်းတစ်ကြောင်း ထပ်ဆက်ပါတယ်။

  5. Line 32print(isinstance(rex, Animal), isinstance(rex, Bird))

    Dog က Animal ရဲ့ subclass ဖြစ်လို့ rex က Animal လည်း ဖြစ်ပါတယ် (True)၊ Bird နဲ့တော့ မသက်ဆိုင်ပါဘူး (False)။

  6. Line 34print([cls.__name__ for cls in Dog.__mro__])

    Python က method ရှာမယ့် အစဉ်ကို ပြပါတယ်: Dog, Animal, object။

You should see
I am Rex. Rex says Woof!
I am Pingu. Pingu makes a sound. It waddles.
True False
True
['Dog', 'Animal', 'object']
Inheritance Visual Guide
Vehicle → Car / Bike လို parent-child relationship ကို OOP visual ထဲမှာမြင်နိုင်ပါတယ်။

Multiple inheritance နဲ့ MRO

Python မှာ class တစ်ခုက parent အများကြီးကို ဆက်ခံလို့ ရပါတယ်။ Parent နှစ်ခုလုံးမှာ နာမည်တူ method ရှိရင် MRO အစဉ်အတိုင်း ပထမဆုံးတွေ့တဲ့ဟာ အနိုင်ရပါတယ်၊ ပုံမှန်အားဖြင့် class ရဲ့ ကွင်းထဲမှာ ဘယ်ကနေ ညာ ရေးထားတဲ့ အစဉ်ပါ။ Mixin တွေ (logging, JSON export လို feature သေးသေးလေး တစ်ခုစီ ပေးတဲ့ class) မှာ ဒီ pattern ကို အသုံးများပါတယ်။

duck.py
class Flyer:
    def move(self):
        return "flies"

class Swimmer:
    def move(self):
        return "swims"

class Duck(Flyer, Swimmer):
    pass

print(Duck().move())                          # flies
print([c.__name__ for c in Duck.__mro__])     # Duck, Flyer, Swimmer, object

Inheritance အစား composition

"has-a" ဆက်ဆံရေးဆိုရင် object တစ်ခုကို attribute အဖြစ် ထည့်ပြီး အလုပ်လွှဲပေးပါ။ Car က Engine ကို ဆက်ခံမယ့်အစား self.engine ထဲမှာ သိမ်းထားရင် runtime မှာ ElectricEngine လို အစားထိုးလို့ ရပြီး Car ကို Engine ရဲ့ method အားလုံး မလိုအပ်ဘဲ ဆက်ခံစရာ မလိုတော့ပါဘူး။

car.py
class Engine:
    def start(self):
        return "engine started"

class Car:
    def __init__(self, engine):
        self.engine = engine          # Car HAS-AN Engine

    def drive(self):
        return self.engine.start() + ", car moving"

print(Car(Engine()).drive())

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

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

Framework တွေက inheritance ကို extension point အဖြစ် အသုံးများပါတယ်။ Django မှာ model တိုင်းက models.Model ကို ဆက်ခံပြီး save(), delete() လို method တွေကို အလကား ရပါတယ်။ Class-based view တွေမှာ ListView ကို ဆက်ခံပြီး get_queryset() တစ်ခုတည်းကို override လုပ်ရင် ကျန်တဲ့ pagination, template rendering အားလုံးကို framework က လုပ်ပေးပါတယ်။

Python ရဲ့ standard library မှာလည်း တွေ့ရပါတယ် — custom exception တွေက Exception ကို ဆက်ခံပြီး unittest test တွေက unittest.TestCase ကို ဆက်ခံပါတယ်။ ဒါပေမယ့် အတွေ့အကြုံရှိတဲ့ team တွေက hierarchy ကို အဆင့် နှစ်ဆင့်၊ သုံးဆင့်ထက် မနက်စေဖို့ ကြိုးစားပါတယ်။ A ကနေ B, B ကနေ C, C ကနေ D ဆက်ခံထားရင် D ရဲ့ method တစ်ခု ဘယ်ကလာလဲ သိဖို့ file လေးခု ဖွင့်ရလို့ပါ။ Payment provider, storage backend လို အစားထိုးချင်တဲ့ အပိုင်းတွေအတွက်တော့ composition ကို ရွေးကြပါတယ်။

အမှားများ

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

1. super().__init__() ခေါ်ဖို့ မေ့တာ

Child မှာ __init__ ရေးလိုက်တာနဲ့ parent ရဲ့ __init__ က အလိုအလျောက် မ run တော့ပါဘူး။ super().__init__(name) မပါရင် self.name မဖန်တီးမိဘဲ နောက်မှ introduce() ခေါ်တဲ့အခါ "AttributeError: 'Bird' object has no attribute 'name'" တက်ပါတယ်။ Error က တကယ့် အမှားရှိတဲ့ နေရာနဲ့ ဝေးတဲ့ နေရာမှာ ပေါ်လို့ ရှာရခက်ပါတယ်။

2. Override မှာ method နာမည် စာလုံးပေါင်းမှားတာ

Dog ထဲမှာ def speek(self): လို့ မှားရေးရင် error မတက်ပါဘူး၊ method အသစ်တစ်ခု ထပ်ဖြစ်သွားပြီး rex.speak() က parent ရဲ့ "makes a sound" ကိုပဲ ပြန်ပေးပါတယ်။ Test တစ်ခုနဲ့ child ရဲ့ output ကို စစ်ပါ၊ type checker သုံးရင် typing.override decorator က ဒီလို ပြဿနာကို ဖမ်းပေးနိုင်ပါတယ်။

3. "has-a" ကို inheritance နဲ့ ရေးတာ

class Car(Engine): လို ရေးရင် Car က Engine ရဲ့ method အားလုံးကို ရပြီး car.check_oil_pressure() လို အဓိပ္ပာယ်မရှိတဲ့ API တွေ ပေါ်လာပါတယ်။ "X is a Y" လို့ ပြောလို့ မရရင် composition ကို သုံးပါ။

Best Practices

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

  • Child class ကို parent နေရာမှာ အစားထိုးသုံးလို့ ရရပါမယ် — Animal လက်ခံတဲ့ function တိုင်းက Dog ကိုလည်း ပြဿနာမရှိဘဲ လက်ခံနိုင်ရပါမယ်။
  • Override လုပ်တဲ့ method က parent နဲ့ parameter အရေအတွက်၊ return value အမျိုးအစား တူအောင် ထားပါ၊ ဒါမှ caller တွေ မပျက်မှာပါ။
  • Hierarchy ကို အဆင့် နှစ်ဆင့်၊ သုံးဆင့်ထက် မနက်စေပါနဲ့၊ ပိုနက်လာရင် composition နဲ့ ပြန်စဉ်းစားပါ။
  • super() ကို argument မပါဘဲ ခေါ်ပါ၊ super(Dog, self) လို ပုံစံဟောင်းက Python 2 ခေတ်ကပါ။

Mini challenge

Mini challenge: Employee နဲ့ Manager

Employee parent class နဲ့ Manager child class ရေးပါ။ Manager က parent ရဲ့ လစာတွက်ချက်မှုကို super() နဲ့ ပြန်သုံးပြီး bonus ထပ်ပေါင်းရပါမယ်။

  • Employee(name, salary) မှာ monthly_pay() (salary / 12, ဒသမ နှစ်နေရာ) နဲ့ describe() ပါရမယ်
  • Manager(name, salary, team_size) က super().__init__() ကို ခေါ်ရမယ်
  • Manager.monthly_pay() က parent ရဲ့ ရလဒ်ကို super() နဲ့ ယူပြီး team member တစ်ယောက်ကို 50 ပေါင်းရမယ်
  • Manager.describe() က parent ရဲ့ စာကြောင်းနောက်မှာ " and leads N people" ဆက်ရမယ်
staff.py
class Employee:
    def __init__(self, name, salary):
        # TODO: store name and yearly salary
        pass

    def monthly_pay(self):
        # TODO: salary / 12 rounded to 2 places
        pass

    def describe(self):
        # TODO: "Hla earns 2000.0 per month"
        pass


class Manager(Employee):
    def __init__(self, name, salary, team_size):
        # TODO: let Employee store name and salary, then keep team_size
        pass

    # TODO: override monthly_pay() and describe() using super()


# TODO: loop over [Employee("Hla", 24000), Manager("Mya", 36000, 4)]
#       and print describe() for each one

ရလဒ်: Output က ဒီလို ထွက်ရပါမယ်: Hla earns 2000.0 per month Mya earns 3200.0 per month and leads 4 people True

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

Manager.monthly_pay() ထဲမှာ return super().monthly_pay() + 50 * self.team_size လို့ ရေးလို့ ရပါတယ်။ Manager.describe() ကလည်း self.monthly_pay() ကို ခေါ်တဲ့ parent version ကို ပြန်သုံးတာမို့ bonus ပါပြီးသား ပမာဏ ပေါ်ပါမယ်။

အဖြေ ကြည့်ရန်
staff.py
class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def monthly_pay(self):
        return round(self.salary / 12, 2)

    def describe(self):
        return f"{self.name} earns {self.monthly_pay()} per month"


class Manager(Employee):
    def __init__(self, name, salary, team_size):
        super().__init__(name, salary)
        self.team_size = team_size

    def monthly_pay(self):
        bonus = 50 * self.team_size
        return super().monthly_pay() + bonus

    def describe(self):
        return super().describe() + f" and leads {self.team_size} people"


staff = [Employee("Hla", 24000), Manager("Mya", 36000, 4)]
for person in staff:
    print(person.describe())
print(isinstance(staff[1], Employee))

Quick Quiz 1 / 3

class A: def hi(self): return "A" ၊ class B(A): def hi(self): return "B" + super().hi() ဆိုရင် B().hi() က ဘာ ပြန်ပေးမလဲ။

Quick Quiz 2 / 3

Child class မှာ __init__ ရေးပြီး super().__init__() မခေါ်ရင် ဘာဖြစ်မလဲ။

Quick Quiz 3 / 3

Report class က PDF ထုတ်ဖို့ PdfWriter object တစ်ခု လိုတယ်။ ဘယ်ဒီဇိုင်းက အကောင်းဆုံးလဲ။

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

  • class Child(Parent): နဲ့ child က parent ရဲ့ attribute နဲ့ method တွေကို ဆက်ခံပါတယ်။
  • နာမည်တူ method ရေးရင် override ဖြစ်ပြီး super() နဲ့ parent version ကို ပြန်သုံးလို့ ရပါတယ်။
  • Child မှာ __init__ ရေးရင် super().__init__(...) ကို ခေါ်ဖို့ မမေ့ပါနဲ့။
  • Method lookup က __mro__ အစဉ်အတိုင်း သွားပြီး "has-a" ဆက်ဆံရေးအတွက် composition ကို ရွေးပါ။

Python Documentation — Classes — Python Software Foundation

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

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

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

Inheritance (Enhanced) | Thuta Learning