OOP และ Data Model
ทุกอย่างใน Python คือ object
หัวข้อที่มีชื่อว่า “ทุกอย่างใน Python คือ object”Python เป็นภาษาที่เน้น object-oriented อย่างเต็มรูปแบบ: จำนวนเต็ม, string, function, module — ทุกค่าล้วนเป็น object ที่มี identity, type และ value
class คือแบบพิมพ์เขียว ส่วน object (หรือ instance) คือสิ่งที่สร้างจาก class นั้นด้วย ClassName(...)
x = 42print(type(x)) # <class 'int'>print(id(x)) # ที่อยู่ในหน่วยความจำSpecial-method protocol
หัวข้อที่มีชื่อว่า “Special-method protocol”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 ที่เรียบง่ายที่สุด
หัวข้อที่มีชื่อว่า “Class ที่เรียบง่ายที่สุด”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 ที่อ่านง่ายสำหรับนักพัฒนา
สิ่งที่ module นี้ครอบคลุม
หัวข้อที่มีชื่อว่า “สิ่งที่ module นี้ครอบคลุม”| บทเรียน | หัวข้อ |
|---|---|
| 1. Classes | class, __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 |
Demo รันได้จริง
หัวข้อที่มีชื่อว่า “Demo รันได้จริง”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))Loading Python runtime (first run only)…