🎩 Lesson 6: Magic Methods (Dunder Methods)
1. Magic Methods ဆိုတာဘာလဲ?
မြန်မာ → Magic methods (dunder methods) ဆိုတာ Python objects တွေကို builtin syntax တွေနဲ့ integrate ပေးတဲ့ hooks တွေပါ။ __init__, __str__, __len__ လို double-underscore methods တွေဟာ constructor, printing, arithmetic, comparisons, iteration, context management စတဲ့ features တွေကို enable/customize လုပ်ပေးတယ်။
English → Magic methods (dunder methods) are hooks that integrate Python objects with builtin syntax. Double-underscore methods enable/customize features like construction, printing, arithmetic, comparisons, iteration, and context management.
2. Common Magic Methods
| Category | Methods |
|---|---|
| Lifecycle | __init__, __new__, __del__ |
| Representation | __repr__, __str__, __format__ |
| Arithmetic | __add__, __sub__, __mul__, __truediv__ |
| Containers | __len__, __getitem__, __iter__ |
3. အကျဉ်းချုပ်
✅ Magic methods let classes play nicely with Python's syntax
✅ Use them to make APIs intuitive and Pythonic
✅ Prioritize correctness, clarity, and performance
# ===== 1. Initialization and Representation =====
class User:
def __init__(self, name, age): # constructor
self.name = name
self.age = age
def __repr__(self): # unambiguous, for developers
return f"User(name={self.name!r}, age={self.age})"
def __str__(self): # human-friendly
return f"{self.name} ({self.age})"
u = User("Sai", 25)
print(f"__repr__: {repr(u)}")
print(f"__str__: {str(u)}")
# ===== 2. Arithmetic Operators =====
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other): # v1 + v2
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(f"\nv1 + v2 = {v1 + v2}")
# ===== 3. Container Methods =====
class Bag:
def __init__(self, items):
self._items = list(items)
def __len__(self): # len(bag)
return len(self._items)
def __getitem__(self, idx): # bag[0]
return self._items[idx]
def __iter__(self): # for x in bag
return iter(self._items)
bag = Bag([1, 2, 3, 4])
print(f"\nlen(bag) = {len(bag)}")
print(f"bag[0] = {bag[0]}")
print(f"Iteration: {[x for x in bag]}")__repr__: User(name='Sai', age=25) __str__: Sai (25) v1 + v2 = Vector(4, 6) len(bag) = 4 bag[0] = 1 Iteration: [1, 2, 3, 4]