ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
ATM စက်ကို စဉ်းစားကြည့်ပါ။ ဘဏ်ရဲ့ ငွေသေတ္တာထဲ လက်နှိုက်ပြီး ငွေယူလို့ မရပါဘူး၊ ခလုတ်တွေ (ငွေထုတ်၊ ငွေသွင်း၊ လက်ကျန်ကြည့်) ကနေပဲ လုပ်ရပါတယ်။ ခလုတ်တိုင်းက လုပ်ခွင့်ရှိမရှိ အရင်စစ်ပါတယ် — လက်ကျန်ထက် ပိုထုတ်လို့ မရပါဘူး။
Encapsulation ဆိုတာ class တစ်ခုကို ATM လို လုပ်တာပါ။ Data (balance) နဲ့ အဲဒီ data ကို ပြောင်းတဲ့ method တွေ (deposit, withdraw) ကို class ထဲမှာ စုထားပြီး အပြင်ကလူတွေကို စစ်ဆေးမှု ပါတဲ့ "ခလုတ်" တွေကနေပဲ ပြောင်းခွင့်ပေးပါတယ်။ ဒါဆိုရင် object က ဘယ်တော့မှ အဓိပ္ပာယ်မရှိတဲ့ အခြေအနေ (အနုတ် balance လို) ထဲ မရောက်တော့ပါဘူး။
Problem → Why → Solution
ပြဿနာ: ဘယ်သူမဆို balance ကို ပြင်လို့ ရနေတယ်
အောက်က class မှာ balance က public attribute သက်သက်ပါ။ withdraw() method ထဲမှာ စစ်ဆေးမှု ရေးထားပေမယ့် code ရဲ့ ဘယ်နေရာကမဆို account.balance = -500 လို့ တိုက်ရိုက် assign လုပ်လို့ ရနေပါတယ်။ Python က ဘာ error မှ မပေးဘဲ လက်ခံလိုက်ပြီး နောက်ပိုင်း interest တွက်တာ၊ report ထုတ်တာ အားလုံး မှားကုန်ပါတယ်။
class BankAccount:
def __init__(self, balance):
self.balance = balance # public, unprotected
def withdraw(self, amount):
if amount <= self.balance: # the rule lives here...
self.balance -= amount
account = BankAccount(1000)
account.balance = -500 # ...but this skips the rule entirely
print(account.balance) # -500ဘာကြောင့် ဒါက အန္တရာယ်ရှိတာလဲ
"balance က အနုတ် မဖြစ်ရ" ဆိုတဲ့ စည်းမျဉ်း (invariant) ကို object တစ်ခုတည်းက မစောင့်ရှောက်နိုင်တော့ပါဘူး၊ code တစ်ခုလုံးမှာ attribute ကို ထိတဲ့ နေရာတိုင်းက စည်းကမ်းလိုက်နာဖို့ မျှော်လင့်နေရပါတယ်။ Bug ပေါ်လာရင်လည်း ဘယ်နေရာက ပြင်သွားလဲ ရှာဖို့ project တစ်ခုလုံးကို ရှာရပါတယ်။ ပြောင်းလဲမှုတိုင်းကို method ဒါမှမဟုတ် property ကနေ ဖြတ်သွားစေရင် စစ်ဆေးမှုက နေရာတစ်ခုတည်းမှာ ရှိနေပါတယ်။
Core concept: convention, name mangling နဲ့ property
Java, C# လို language တွေမှာ private keyword က တကယ် ပိတ်ပင်ပေမယ့် Python မှာ attribute အားလုံးကို နည်းလမ်းတစ်ခုခုနဲ့ ဝင်ကြည့်လို့ ရပါတယ်။ Python ရဲ့ encapsulation က "လုံးဝ ပိတ်ထားတာ" ထက် "ရှင်းလင်းတဲ့ public interface နဲ့ သဘောတူညီချက် (convention)" ကို အခြေခံပါတယ်။ Python community မှာ ဒါကို "we are all consenting adults here" လို့ ပြောလေ့ရှိပါတယ်။
| ပုံစံ | အဓိပ္ပာယ် |
|---|---|
| name | Public — ဘယ်သူမဆို ဖတ်၊ ပြင်လို့ ရတဲ့ interface ရဲ့ အစိတ်အပိုင်း |
| _name | Internal — "class အပြင်က မထိပါနဲ့" ဆိုတဲ့ convention၊ Python က မပိတ်ပါ |
| __name | Name mangling — _ClassName__name လို့ နာမည်ပြောင်းပေးတယ်၊ subclass နာမည်တိုက်မှု ရှောင်ဖို့ |
Single underscore (_balance) က တခြား developer တွေကို "ဒါက implementation detail ပါ၊ နောက် version မှာ ပြောင်းနိုင်တယ်" လို့ ပြောတာပါ။ Double underscore (__pin) ကတော့ Python က attribute နာမည်ကို _BankAccount__pin လို့ ပြောင်းရေးပေးပါတယ်၊ ဒါကို name mangling လို့ ခေါ်ပါတယ်။ ရည်ရွယ်ချက်က subclass တစ်ခုက __pin ဆိုတဲ့ နာမည်တူ attribute ကို မတော်တဆ ဖုံးမိတာကို ကာကွယ်ဖို့ပါ၊ security အတွက် မဟုတ်ပါဘူး — obj._BankAccount__pin လို့ ရေးရင် ဖတ်လို့ ရနေဆဲပါ။
တကယ့် ကာကွယ်မှုက public method နဲ့ property တွေကနေ လာပါတယ်။ @property decorator က method တစ်ခုကို attribute လို ဖတ်လို့ရအောင် လုပ်ပေးပါတယ် — acct.balance လို့ ကွင်းမပါဘဲ ဖတ်ပေမယ့် နောက်ကွယ်မှာ function run ပါတယ်။ Setter မရေးထားရင် အဲဒီ attribute က read-only ဖြစ်ပြီး assign လုပ်ရင် AttributeError တက်ပါတယ်။ @name.setter ရေးထားရင်တော့ assign လုပ်တိုင်း validation run ပါတယ်။
ဒါကြောင့် Python မှာ get_balance()/set_balance() method တွေ ကြိုရေးစရာ မလိုပါဘူး။ ရိုးရိုး public attribute နဲ့ စပြီး နောက်မှ စစ်ဆေးမှု လိုလာရင် property အဖြစ် ပြောင်းလိုက်ရင် caller တွေရဲ့ code (obj.x = 5) ကို တစ်ကြောင်းမှ ပြင်စရာ မလိုပါဘူး။
Property က validation အတွက်ပဲ မဟုတ်ပါဘူး၊ တွက်ချက်ထားတဲ့ value (computed value) အတွက်လည်း သုံးပါတယ်။ ဥပမာ Temperature မှာ celsius ကိုပဲ သိမ်းပြီး fahrenheit ကို ဖတ်တိုင်း တွက်ပေးရင် value နှစ်ခု တစ်ခုနဲ့တစ်ခု မကိုက်ညီတော့တဲ့ ပြဿနာ ဘယ်တော့မှ မဖြစ်ပါဘူး။ Caller တွေက internal representation ကို မမှီခိုတော့လို့ နောက်မှ သိမ်းပုံကို ပြောင်းလည်း ပြဿနာ မရှိပါဘူး။
- Caller က method/property ကို ခေါ်
- Gate က စည်းမျဉ်းကို စစ်
- မှန်ရင် _data ကို ပြင်
- မမှန်ရင် error raise, state မပြောင်း
Underscore က "မထိပါနဲ့" လို့ ပြောရုံပါ၊ တကယ်ကာကွယ်တာက စစ်ဆေးတဲ့ gate ပါ။
အထွေထွေ ပုံစံ
class Thing:
def __init__(self, value):
self.value = value # runs the setter below
@property
def value(self): # read: obj.value
return self._value
@value.setter
def value(self, new): # write: obj.value = new
# validate new, raise ValueError if it breaks a rule
self._value = newData အစစ်ကို _value ထဲမှာ သိမ်းပြီး @property က ဖတ်တဲ့ ဂိတ်၊ @value.setter က ရေးတဲ့ ဂိတ် ဖြစ်ပါတယ်။ __init__ ကလည်း self.value = value လို့ setter ကနေ ဖြတ်လို့ object အသစ်တွေပါ စစ်ဆေးမှု ခံရပါတယ်။ Setter မရေးရင် read-only ဖြစ်ပါတယ်။
Example: ကာကွယ်ထားတဲ့ BankAccount
Balance ကို _balance ထဲမှာ သိမ်းပြီး balance property (setter မပါ) နဲ့ ဖတ်ခွင့်ပဲ ပေးပါတယ်။ ငွေပမာဏ ပြောင်းဖို့ deposit() နဲ့ withdraw() ကနေပဲ ရပြီး နှစ်ခုလုံးက စည်းမျဉ်း စစ်ပါတယ်။ နောက်ဆုံးမှာ စည်းမျဉ်း ချိုးဖောက်ဖို့ နှစ်ကြိမ် ကြိုးစားကြည့်ပါတယ်။
class BankAccount:
def __init__(self, owner, balance=0):
if balance < 0:
raise ValueError("opening balance cannot be negative")
self.owner = owner # public: free to read and change
self._balance = balance # internal: change it via methods
@property
def balance(self): # read like an attribute
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("deposit must be positive")
self._balance += amount
def withdraw(self, amount):
if not 0 < amount <= self._balance:
raise ValueError(f"cannot withdraw {amount}")
self._balance -= amount
acct = BankAccount("Sai", 1000)
acct.deposit(500)
acct.withdraw(200)
print(acct.owner, acct.balance)
try:
acct.withdraw(5000)
except ValueError as e:
print("blocked:", e)
try:
acct.balance = -500 # no setter, so this is refused
except AttributeError:
print("blocked: balance is read-only")
print(acct.balance)Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Line 6
self._balance = balance # internal: change it via methodsUnderscore တစ်ခုက "class အပြင်က တိုက်ရိုက် မပြင်ပါနဲ့" ဆိုတဲ့ convention ပါ။ Python က တားမှာ မဟုတ်ပေမယ့် linter နဲ့ code reviewer တွေက သတိပေးပါတယ်။
- Lines 8-10
@propertyacct.balance လို့ ကွင်းမပါဘဲ ဖတ်လို့ ရပါတယ်။ Setter မရေးထားလို့ read-only ပါ။
- Line 18
if not 0 < amount <= self._balance:Chained comparison နဲ့ amount က 0 ထက်ကြီးပြီး balance ထက် မကျော်ရင်ပဲ ဆက်သွားပါတယ်၊ မဟုတ်ရင် ValueError raise လုပ်ပြီး balance ကို မထိပါဘူး။
- Line 34
acct.balance = -500 # no setter, so this is refusedProblem section မှာ အလုပ်ဖြစ်ခဲ့တဲ့ line ပါ။ အခု property မှာ setter မရှိလို့ AttributeError တက်ပြီး balance က 1300 အတိုင်း ကျန်ပါတယ်။
Sai 1300
blocked: cannot withdraw 5000
blocked: balance is read-only
1300Name mangling ကို မျက်စိနဲ့ မြင်ကြည့်ခြင်း
__code ဆိုတဲ့ နာမည်က object ပေါ်မှာ တကယ်တော့ _Vault__code ဆိုပြီး သိမ်းထားပါတယ်။ ဒါကြောင့် hasattr(v, "__code") က False ပြန်ပေမယ့် mangled နာမည်နဲ့ ဖတ်ရင် value ကို ရနေဆဲပါ။ Password, API key လို လျှို့ဝှက်ချက်တွေကို double underscore နဲ့ "ဝှက်" လို့ ရတယ်လို့ မထင်ပါနဲ့။
class Vault:
def __init__(self):
self.__code = 1234 # name-mangled to _Vault__code
v = Vault()
print(hasattr(v, "__code")) # False
print(v._Vault__code) # 1234: still reachable, not securityget_name()/set_name() အစား property
Getter/setter method တွေ (get_name(), set_name()) လည်း အလုပ်ဖြစ်ပါတယ်၊ ဒါပေမယ့် Python မှာ property က ပိုသဘာဝကျပါတယ်။ အောက်က Person မှာ p.name = "Aye" လို့ ရိုးရိုး assign လုပ်ပေမယ့် setter က space တွေကို ဖြတ်ပြီး အလွတ် နာမည်ကို ငြင်းပါတယ်။
class Person:
def __init__(self, name):
self.name = name # goes through the setter below
@property
def name(self):
return self._name
@name.setter
def name(self, value):
value = value.strip()
if not value:
raise ValueError("name cannot be empty")
self._name = value
p = Person(" Sai ")
p.name = "Aye"
print(p.name) # Aye
try:
p.name = " "
except ValueError as e:
print(e) # name cannot be emptyလက်တွေ့ project တွေမှာ
Real project တွေမှာ ဘယ်လို သုံးလဲ
E-commerce system တစ်ခုမှာ Order object ရဲ့ status က "pending → paid → shipped" အစဉ်အတိုင်းပဲ ပြောင်းရပါမယ်။ order.status = "shipped" လို့ ဘယ်နေရာကမဆို ရေးခွင့်ပေးထားရင် ငွေမပေးရသေးတဲ့ order ကို ပို့မိနိုင်ပါတယ်။ order.mark_shipped() method တစ်ခုက status "paid" ဖြစ်မှ ခွင့်ပြုရင် အဲဒီ စည်းမျဉ်းက နေရာတစ်ခုတည်းမှာ ရှိနေပါတယ်။
Library ရေးတဲ့သူတွေအတွက်လည်း encapsulation က အရေးကြီးပါတယ်။ _ နဲ့ စတဲ့ name တွေကို public API မဟုတ်လို့ နောက် version မှာ ပြောင်းလို့ ရပြီး user တွေရဲ့ code မပျက်ပါဘူး။ Django model တွေ၊ pandas DataFrame တွေမှာ df.shape လို property တွေက တွက်ချက်ထားတဲ့ value ကို attribute လို ပြပါတယ်။ Configuration object တွေမှာလည်း port number က 1-65535 ကြားမှာပဲ ဖြစ်ရမယ်လို validation ကို setter ထဲမှာ ထည့်လေ့ရှိပါတယ်၊ ဒါမှ မမှန်တဲ့ config က program စတဲ့ အချိန်မှာပဲ ရှင်းလင်းတဲ့ error နဲ့ ရပ်သွားမှာပါ။
အမှားများ
အဖြစ်များတဲ့ အမှားတွေ
1. __name ကို security လို့ ထင်တာ
self.__password လို့ ရေးလိုက်ရင် ဘေးကင်းပြီလို့ ထင်တတ်ပါတယ်၊ ဒါပေမယ့် obj._User__password နဲ့ ဖတ်လို့ ရပြီး vars(obj) ထဲမှာလည်း မြင်ရပါတယ်။ လျှို့ဝှက်ချက်တွေကို hash လုပ်ပြီး သိမ်းပါ၊ log ထဲ မထုတ်ပါနဲ့၊ __repr__ ထဲမှာ မပြပါနဲ့။
2. Property ထဲမှာ ကိုယ့်နာမည်ကိုယ် ပြန်ခေါ်တာ
@property def name(self): return self.name လို့ ရေးရင် self.name က property ကိုပဲ ပြန်ခေါ်လို့ RecursionError တက်ပါတယ်။ Setter ထဲမှာ self.name = value ရေးရင်လည်း အတူတူပါပဲ။ Data အစစ်ကို self._name လို တခြား နာမည်နဲ့ သိမ်းရပါမယ်။
3. __init__ မှာ validation ကို ကျော်တာ
Setter ထဲမှာ စစ်ထားပေမယ့် __init__ ထဲမှာ self._celsius = celsius လို့ တိုက်ရိုက် ရေးရင် Temperature(-500) လို မမှန်တဲ့ object ကို ဖန်တီးလို့ ရသွားပါတယ်။ __init__ ထဲမှာ self.celsius = celsius လို့ property ကနေ ဖြတ်ပါ။
4. Attribute တိုင်းအတွက် getter/setter ရေးတာ
စစ်ဆေးမှု ဘာမှ မပါတဲ့ get_x()/set_x() တွေက code ကို ရှည်စေရုံပါ။ စည်းမျဉ်း တကယ်ရှိမှ property သုံးပါ။
Best Practices
အကောင်းဆုံး အလေ့အကျင့်များ
- Object ရဲ့ invariant တွေ ("balance က အနုတ် မဖြစ်ရ" လို) ကို class docstring ထဲမှာ ရေးထားပြီး ပြောင်းလဲမှုတိုင်း အဲဒါကို စစ်ပါ။
- Internal helper နဲ့ attribute တွေကို single underscore နဲ့ စပါ၊ double underscore ကို subclass နာမည်တိုက်မှု တကယ် စိုးရိမ်ရမှ သုံးပါ။
- Property getter တွေကို မြန်မြန်နဲ့ side effect မရှိအောင် ထားပါ၊ network call လို အလုပ်လေးတွေအတွက် ရိုးရိုး method ကို သုံးပါ။
Mini challenge
Mini challenge: Temperature class
Celsius ကို validate လုပ်တဲ့ property နဲ့ Fahrenheit ကို တွက်ပေးတဲ့ read-only property ပါတဲ့ Temperature class ရေးပါ။
- celsius setter က -273.15 (absolute zero) အောက် value ကို ValueError နဲ့ ငြင်းရမယ်
- __init__ ကလည်း setter ကနေ ဖြတ်ရမယ်၊ ဒါမှ Temperature(-300) မအောင်မြင်မှာပါ
- fahrenheit က celsius × 9 / 5 + 32 ကို ဒသမ တစ်နေရာနဲ့ ပြန်ပေးရမယ်၊ setter မပါရ
- Celsius ကို 100 လို့ ပြောင်းပြီး fahrenheit ပြောင်းသွားတာကို ပြရမယ်
class Temperature:
ABSOLUTE_ZERO = -273.15
def __init__(self, celsius):
# TODO: assign through the property so the check runs
pass
# TODO: @property celsius that returns the stored value
# TODO: @celsius.setter that raises ValueError below ABSOLUTE_ZERO
# TODO: read-only @property fahrenheit (round to 1 decimal)
# TODO: t = Temperature(25); print celsius and fahrenheit
# TODO: set celsius to 100 and print fahrenheit again
# TODO: show that -300 and assigning to fahrenheit are both rejectedရလဒ်: Output က ဒီလို ထွက်ရပါမယ်: 25 77.0 212.0 rejected: -300 is below absolute zero rejected: fahrenheit is read-only 100
အရိပ်အမြွက် ကြည့်ရန်
Data အစစ်ကို self._celsius ထဲ သိမ်းပါ။ fahrenheit အတွက် @property ပဲ ရေးပြီး setter မရေးရင် t.fahrenheit = 50 က AttributeError ပေးပါတယ်။
အဖြေ ကြည့်ရန်
class Temperature:
ABSOLUTE_ZERO = -273.15
def __init__(self, celsius):
self.celsius = celsius # validated by the setter
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < self.ABSOLUTE_ZERO:
raise ValueError(f"{value} is below absolute zero")
self._celsius = value
@property
def fahrenheit(self):
return round(self._celsius * 9 / 5 + 32, 1)
t = Temperature(25)
print(t.celsius, t.fahrenheit)
t.celsius = 100
print(t.fahrenheit)
try:
t.celsius = -300
except ValueError as e:
print("rejected:", e)
try:
t.fahrenheit = 50
except AttributeError:
print("rejected: fahrenheit is read-only")
print(t.celsius)Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Encapsulation က data ကို စစ်ဆေးမှုပါတဲ့ method/property ကနေပဲ ပြောင်းခွင့်ပေးပြီး object ရဲ့ invariant ကို ကာကွယ်ပါတယ်။
- _name က "internal" convention ဖြစ်ပြီး __name က name mangling ပါ၊ နှစ်ခုလုံး security မဟုတ်ပါဘူး။
- @property က method ကို attribute လို ဖတ်စေပြီး setter မပါရင် read-only ဖြစ်ပါတယ်။
- Public attribute နဲ့ စပြီး စည်းမျဉ်း လိုလာမှ property ပြောင်းပါ၊ caller code မပြောင်းရပါဘူး။
Python Documentation — Classes — Python Software Foundation