ข้ามไปยังเนื้อหา

OOP และ Data Model

Python เป็นภาษาที่เน้น object-oriented อย่างเต็มรูปแบบ: จำนวนเต็ม, string, function, module — ทุกค่าล้วนเป็น object ที่มี identity, type และ value class คือแบบพิมพ์เขียว ส่วน object (หรือ instance) คือสิ่งที่สร้างจาก class นั้นด้วย ClassName(...)

x = 42
print(type(x)) # <class 'int'>
print(id(x)) # ที่อยู่ในหน่วยความจำ

Python เปิดเผย operation ของ built-in แทบทั้งหมดผ่าน dunder methods (เมธอดที่มี double-underscore เช่น __init__, __repr__, __add__) เมื่อเขียน a + b Python จะเรียก a.__add__(b) เมื่อเขียน len(obj) Python จะเรียก obj.__len__() เมื่อเขียน repr(obj) Python จะเรียก obj.__repr__()

กลไกนี้เรียกว่า Python Data Model — ทำให้ class ของเราผสานเข้ากับ built-in syntax และฟังก์ชันของ standard library ได้อย่างราบรื่น

class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __repr__(self) -> str:
return f"Point({self.x}, {self.y})"
  • __init__ คือ initialiser — ทำงานทันทีหลังสร้าง object และกำหนด instance attribute
  • __repr__ ให้ string representation ที่อ่านง่ายสำหรับนักพัฒนา
บทเรียนหัวข้อ
1. Classesclass, __init__, instance vs class attributes, inheritance
2. Dunder methods__repr__, __eq__, __len__, __getitem__, __add__
3. Properties@property, computed attributes, @classmethod, @staticmethod
4. Dataclasses@dataclass, defaults, field, frozen=True
class Point:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __repr__(self) -> str:
return f"Point({self.x}, {self.y})"
def __add__(self, other: "Point") -> "Point":
return Point(self.x + other.x, self.y + other.y)
p1 = Point(1, 2)
p2 = Point(3, 4)
print(p1)
print(p1 + p2)
print(type(p1))
print(isinstance(p1, Point))
Dunder method ใดที่ทำงานเมื่อเขียน `obj = MyClass(1, 2)`?
Python เรียก method ใดภายใต้ hood เมื่อเขียน `len(my_list)`?
คำศัพท์ใดหมายถึงระบบ dunder method ที่ผสาน class เข้ากับ Python syntax?
ข้อความใดเกี่ยวกับ object ใน Python เป็นความจริง?