

Class Python คือ — คู่มือฉบับสมบูรณ์ 2026 | SiamCafe Blog
หากคุณกำลังเดินทางอยู่ในโลกของการเขียนโปรแกรมด้วยภาษา Python แน่นอนว่าคุณต้องเคยได้ยินคำว่า “Class” หรือ “คลาส” อยู่บ่อยครั้ง Class เป็นหนึ่งในแนวคิดหลักของกระบวนทัศน์การเขียนโปรแกรมเชิงวัตถุ (Object-Oriented Programming: OOP) ที่ทำให้ Python มีพลังและความยืดหยุ่นอย่างมหาศาล คู่มือฉบับสมบูรณ์ปี 2026 นี้จะพาคุณดำดิ่งไปสู่แก่นแท้ของ Class ใน Python ตั้งแต่พื้นฐานจนถึงเทคนิคขั้นสูง พร้อมตัวอย่างโค้ด โครงสร้าง HTML ที่ชัดเจน และแนวทางการใช้งานจริง เพื่อให้คุณไม่เพียงแค่เข้าใจทฤษฎี แต่สามารถนำไปประยุกต์สร้างซอฟต์แวร์ที่มีประสิทธิภาพได้จริง
Class ใน Python คืออะไร? พื้นฐานของ OOP
Class (คลาส) ใน Python คือ “พิมพ์เขียว” (Blueprint) หรือ “แบบแผน” สำหรับการสร้างวัตถุ (Object) มันเป็นโครงสร้างที่ใช้กำหนดคุณลักษณะ (Attributes) และพฤติกรรม (Methods) ของวัตถุที่สร้างขึ้นจากคลาสนั้น นึกภาพคลาสเป็นแบบแปลนบ้าน ที่ระบุว่าบ้านต้องมีกี่ห้อง มีหน้าต่างแบบไหน ส่วน Object ก็คือบ้านจริงๆ ที่สร้างขึ้นมาจากแบบแปลนนั้น เราสามารถสร้างบ้านได้หลายหลังจากแบบแปลนเดียวกัน
การเขียนโปรแกรมเชิงวัตถุด้วยคลาสช่วยให้โค้ดเป็นระบบ ง่ายต่อการจัดการและขยายขนาด (Scalable) หลักการสำคัญของ OOP ที่คลาสนำมาใช้มี 4 ประการคือ:
- การห่อหุ้ม (Encapsulation): การจัดกลุ่มข้อมูล (Attributes) และเมธอด (Methods) ที่เกี่ยวข้องกันไว้ในคลาสเดียว และสามารถควบคุมการเข้าถึงได้
- การสืบทอด (Inheritance): ความสามารถของคลาสหนึ่ง (คลาสลูก) ในการรับคุณสมบัติและเมธอดจากอีกลคลาสหนึ่ง (คลาสแม่) ได้
- พหุสัณฐาน (Polymorphism): ความสามารถของเมธอดเดียวกันในการแสดงพฤติกรรมที่แตกต่างกันไปขึ้นอยู่กับวัตถุที่เรียกใช้
- การซ่อนข้อมูล (Abstraction): การซ่อนรายละเอียดที่ซับซ้อนและแสดงเฉพาะฟีเจอร์ที่จำเป็นต่อผู้ใช้
โครงสร้างพื้นฐานของคลาส
การประกาศคลาสใน Python ใช้คำสั่ง class ตามด้วยชื่อคลาส (ควรขึ้นต้นด้วยตัวพิมพ์ใหญ่) และเครื่องหมายโคลอน (:)
class Employee:
"""คลาสสำหรับแสดงข้อมูลพนักงาน""" # docstring
# Class Attribute (คุณลักษณะระดับคลาส)
company = "SiamCafe Corp"
# Initializer / Constructor
def __init__(self, name, position, salary):
# Instance Attributes (คุณลักษณะระดับวัตถุ)
self.name = name
self.position = position
self.salary = salary
# Instance Method (เมธอดระดับวัตถุ)
def introduce(self):
return f"สวัสดีครับ ผมชื่อ {self.name} ตำแหน่ง {self.position}"
# Method อื่นๆ
def annual_bonus(self, percent):
return self.salary * percent / 100
# การสร้างวัตถุ (Instance)
emp1 = Employee("สมชาย", "Software Developer", 50000)
print(emp1.introduce()) # ผลลัพธ์: สวัสดีครับ ผมชื่อ สมชาย ตำแหน่ง Software Developer
print(f"โบนัส: {emp1.annual_bonus(10)} บาท") # ผลลัพธ์: โบนัส: 5000.0 บาท
องค์ประกอบหลักภายในคลาส: Attributes และ Methods
การทำงานของคลาสอาศัยองค์ประกอบหลักสองส่วนคือ Attributes (ข้อมูล) และ Methods (ฟังก์ชัน) ซึ่งสามารถแบ่งประเภทได้ตามขอบเขตการทำงาน
ประเภทของ Attributes
| ประเภท | คำนิยาม | ขอบเขต | ตัวอย่าง |
|---|---|---|---|
| Instance Attributes | คุณลักษณะที่เป็นของวัตถุแต่ละชิ้นที่สร้างจากคลาส กำหนดในเมธอด __init__ |
เฉพาะวัตถุนั้น | self.name, self.salary |
| Class Attributes | คุณลักษณะที่เป็นของคลาสทั้งหมด วัตถุทุกชิ้นที่สร้างจากคลาสนี้แชร์ค่าเดียวกัน | ทั้งคลาส | company = "SiamCafe Corp" |
ประเภทของ Methods
class Calculator:
# 1. Instance Method (ต้องมี self เป็นพารามิเตอร์แรก)
def add(self, a, b):
return a + b
# 2. Class Method (ใช้ @classmethod, พารามิเตอร์แรกคือ cls)
@classmethod
def get_class_info(cls):
return f"คลาสนี้ชื่อ {cls.__name__} ใช้สำหรับคำนวณ"
# 3. Static Method (ใช้ @staticmethod, ไม่มี self หรือ cls)
@staticmethod
def welcome_message():
return "ยินดีต้อนรับสู่เครื่องคิดเลข"
# 4. Special/Dunder Methods (ขึ้นต้นและลงท้ายด้วย __)
def __str__(self):
return "นี่คือวัตถุของคลาส Calculator"
# การใช้งาน
calc = Calculator()
print(calc.add(5, 3)) # Instance Method: 8
print(Calculator.get_class_info()) # Class Method
print(Calculator.welcome_message()) # Static Method
print(calc) # Special Method: นี่คือวัตถุของคลาส Calculator
หลักการสำคัญของ OOP ใน Python
การสืบทอด (Inheritance)
การสืบทอดช่วยให้เราสร้างคลาสใหม่ (คลาสลูก) โดยอาศัยคุณสมบัติจากคลาสที่มีอยู่แล้ว (คลาสแม่) ได้ ช่วยลดการเขียนโค้ดซ้ำซ้อนและสร้างความสัมพันธ์แบบ “is-a”
class Vehicle: # คลาสแม่ (Parent Class)
def __init__(self, brand, model):
self.brand = brand
self.model = model
def start_engine(self):
return "เครื่องยนต์ทำงาน..."
class Car(Vehicle): # คลาสลูก (Child Class) สืบทอดจาก Vehicle
def __init__(self, brand, model, num_doors):
# เรียกใช้ Constructor ของคลาสแม่ด้วย super()
super().__init__(brand, model)
self.num_doors = num_doors
# Override เมธอดของคลาสแม่
def start_engine(self):
base_sound = super().start_engine()
return f"{base_sound} รถยนต์ {self.brand} {self.model} พร้อมออกตัว!"
class ElectricCar(Car): # สืบทอดต่อเป็นหลายระดับ
def __init__(self, brand, model, num_doors, battery_capacity):
super().__init__(brand, model, num_doors)
self.battery_capacity = battery_capacity
def start_engine(self):
return "มอเตอร์ไฟฟ้าทำงานเงียบๆ... พร้อม!"
# การใช้งาน
my_car = Car("Toyota", "Camry", 4)
print(my_car.start_engine()) # ผลลัพธ์: เครื่องยนต์ทำงาน... รถยนต์ Toyota Camry พร้อมออกตัว!
my_tesla = ElectricCar("Tesla", "Model 3", 4, 75)
print(my_tesla.start_engine()) # ผลลัพธ์: มอเตอร์ไฟฟ้าทำงานเงียบๆ... พร้อม!
การห่อหุ้ม (Encapsulation) และการควบคุมการเข้าถึง
Python ไม่มี Access Modifiers (เช่น private, public) แบบภาษาอื่นอย่างเข้มงวด แต่ใช้ข้อตกลงการตั้งชื่อ (Name Mangling) แทน
- Public: ชื่อธรรมดา (เช่น
name) – เข้าถึงได้จากทุกที่ - Protected: ขึ้นต้นด้วย underscore หนึ่งตัว (เช่น
_salary) – เป็นข้อตกลงว่า “ไม่ควร” เข้าถึงจากนอกคลาสโดยตรง แต่ Python ไม่ห้าม - Private: ขึ้นต้นด้วย underscore สองตัว (เช่น
__secret_key) – Python จะทำ Name Mangling ทำให้เข้าถึงจากภายนอกได้ยาก
class BankAccount:
def __init__(self, account_holder, initial_balance):
self.account_holder = account_holder # Public
self._bank_code = "SCB" # Protected (convention)
self.__balance = initial_balance # Private (mangled to _BankAccount__balance)
# Getter และ Setter สำหรับการเข้าถึง attribute แบบ private
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
# Property Decorator (วิธี Pythonic ในการสร้าง getter/setter)
@property
def balance(self):
return self.__balance
@balance.setter
def balance(self, amount):
if amount >= 0:
self.__balance = amount
else:
print("ยอดคงเหลือไม่สามารถเป็นลบได้")
account = BankAccount("สมหญิง", 1000)
print(account.account_holder) # เข้าถึงได้: สมหญิง
print(account._bank_code) # เข้าถึงได้แต่ไม่ควร: SCB
# print(account.__balance) # ERROR: AttributeError
print(account._BankAccount__balance) # เข้าถึงได้แบบตรงๆ (แต่ห้ามทำ!) : 1000
print(account.get_balance()) # วิธีที่ถูกต้อง: 1000
account.balance = 1500 # ใช้ setter ของ property
print(account.balance) # ใช้ getter ของ property: 1500
พหุสัณฐาน (Polymorphism)
พหุสัณฐานหมายถึงความสามารถของเมธอดหรือฟังก์ชันเดียวกันในการทำงานแตกต่างกันไปขึ้นอยู่กับประเภทของวัตถุ
class Cat:
def sound(self):
return "แมวร้อง: เหมียว"
class Dog:
def sound(self):
return "หมาร้อง: โฮ่ง"
class Duck:
def sound(self):
return "เป็ดร้อง: ก้าบ"
# ฟังก์ชันที่แสดง Polymorphism
def animal_concert(animals):
for animal in animals:
print(animal.sound()) # เมธอด .sound() ถูกเรียกตามประเภทของวัตถุ
# สร้างลิสต์ของวัตถุต่างคลาสกัน
pets = [Cat(), Dog(), Duck()]
animal_concert(pets)
# ผลลัพธ์:
# แมวร้อง: เหมียว
# หมาร้อง: โฮ่ง
# เป็ดร้อง: ก้าบ
Best Practices และแนวทางการออกแบบคลาสในปี 2026
การเขียนคลาสที่ดีต้องคำนึงถึงการบำรุงรักษา ความอ่านง่าย และการขยายตัวในอนาคต
หลักการ SOLID สำหรับการออกแบบคลาส
- S – Single Responsibility Principle: คลาสหนึ่งคลาสควรมีหน้าที่เดียวเท่านั้น
- O – Open/Closed Principle: คลาสควรเปิดให้ขยายได้ แต่ปิดสำหรับการแก้ไข
- L – Liskov Substitution Principle: วัตถุของคลาสลูกควรสามารถแทนที่วัตถุของคลาสแม่ได้โดยไม่ทำให้ระบบผิดพลาด
- I – Interface Segregation Principle: ไม่ควรบังคับให้คลาสต้อง implement เมธอดที่ไม่ได้ใช้
- D – Dependency Inversion Principle: ขึ้นต่อกับ abstraction (เช่น abstract class) ไม่ใช่ concrete class
เทคนิคการออกแบบคลาสแบบ Pythonic
- ใช้
@dataclass(จากโมดูลdataclasses) สำหรับคลาสที่เก็บข้อมูลอย่างง่าย - ใช้ Type Hints เพื่อเพิ่มความชัดเจนของประเภทข้อมูล
- ใช้ Composition แทน Inheritance เมื่อเหมาะสม (“has-a” ดีกว่า “is-a” ในบางสถานการณ์)
- เขียน Docstring ที่ชัดเจนสำหรับคลาสและเมธอดสำคัญ
- ใช้ Magic Methods (Dunder Methods) อย่างมีประสิทธิภาพ
กรณีศึกษาและการประยุกต์ใช้จริง
Case Study 1: ระบบจัดการสินค้าในร้านค้าออนไลน์
ลองออกแบบคลาสสำหรับระบบจัดการสินค้าขนาดเล็ก
from datetime import datetime
from typing import List, Optional
class Product:
def __init__(self, product_id: int, name: str, price: float, stock: int):
self.product_id = product_id
self.name = name
self.price = price
self.stock = stock
self.created_at = datetime.now()
def reduce_stock(self, quantity: int) -> bool:
if self.stock >= quantity:
self.stock -= quantity
return True
return False
def __repr__(self):
return f"Product(id={self.product_id}, name='{self.name}', price={self.price}, stock={self.stock})"
class ShoppingCart:
def __init__(self):
self.items = [] # List of tuples (product, quantity)
def add_item(self, product: Product, quantity: int):
if product.reduce_stock(quantity):
self.items.append((product, quantity))
print(f"เพิ่ม {product.name} จำนวน {quantity} ชิ้นลงในตะกร้า")
else:
print(f"สินค้า {product.name} มีไม่พอ")
def calculate_total(self) -> float:
return sum(product.price * quantity for product, quantity in self.items)
def checkout(self):
total = self.calculate_total()
print(f"ชำระเงินทั้งหมด: {total:.2f} บาท")
# Logic สำหรับบันทึกลงฐานข้อมูลหรือระบบอื่นๆ
self.items.clear()
# การใช้งาน
iphone = Product(101, "iPhone 15", 32900.0, 50)
macbook = Product(102, "MacBook Air M3", 42900.0, 20)
cart = ShoppingCart()
cart.add_item(iphone, 2)
cart.add_item(macbook, 1)
cart.checkout()
Case Study 2: ระบบจัดการผู้ใช้และสิทธิ์ (User Authentication)
ตัวอย่างการออกแบบคลาสสำหรับระบบจัดการผู้ใช้ด้วยการสืบทอด
from abc import ABC, abstractmethod
import hashlib
class User(ABC):
def __init__(self, username: str, email: str):
self.username = username
self.email = email
self.__password_hash = None
self.is_active = True
def set_password(self, password: str):
# ในทางปฏิบัติควรใช้ library เช่น bcrypt หรือ argon2-cffi
self.__password_hash = hashlib.sha256(password.encode()).hexdigest()
def check_password(self, password: str) -> bool:
if self.__password_hash:
return self.__password_hash == hashlib.sha256(password.encode()).hexdigest()
return False
@abstractmethod
def get_role(self) -> str:
pass
def __str__(self):
return f"User: {self.username} ({self.email})"
class Customer(User):
def __init__(self, username: str, email: str, shipping_address: str):
super().__init__(username, email)
self.shipping_address = shipping_address
self.loyalty_points = 0
def get_role(self) -> str:
return "customer"
def add_loyalty_points(self, points: int):
self.loyalty_points += points
class Admin(User):
def __init__(self, username: str, email: str, admin_level: int = 1):
super().__init__(username, email)
self.admin_level = admin_level
self.permissions = ["read", "write", "delete"]
def get_role(self) -> str:
return f"admin (ระดับ {self.admin_level})"
def can_delete(self) -> bool:
return "delete" in self.permissions
# การใช้งาน
customer = Customer("john_doe", "[email protected]", "123 Bangkok")
customer.set_password("securePass123")
print(customer.check_password("securePass123")) # True
print(customer.get_role()) # customer
admin = Admin("admin_siam", "[email protected]", 2)
print(admin.get_role()) # admin (ระดับ 2)
print(admin.can_delete()) # True
เทรนด์และฟีเจอร์ใหม่ล่าสุด (อัปเดต 2026)
โลกของ Python ยังคงพัฒนาอย่างต่อเนื่อง นี่คือแนวโน้มและฟีเจอร์ที่เกี่ยวข้องกับการทำงานกับคลาสในปี 2026:
1. Pattern Matching (Python 3.10+) กับการทำงานกับคลาส
Structural Pattern Matching ช่วยให้การตรวจสอบประเภทและโครงสร้างของวัตถุทำได้ง่ายและอ่านง่ายขึ้น
class Notification:
def __init__(self, type: str, message: str, user_id: int):
self.type = type
self.message = message
self.user_id = user_id
def handle_notification(notif: Notification):
match notif:
case Notification(type="email", message=msg, user_id=uid):
print(f"ส่งอีเมลถึงผู้ใช้ {uid}: {msg}")
case Notification(type="sms", message=msg):
print(f"ส่ง SMS: {msg}")
case Notification(type="push", user_id=uid):
print(f"ส่ง Push Notification ถึงผู้ใช้ {uid}")
case _:
print("ประเภทการแจ้งเตือนไม่รู้จัก")
# การใช้งาน
email_notif = Notification("email", "ยืนยันการสั่งซื้อของคุณ", 101)
handle_notification(email_notif) # ผลลัพธ์: ส่งอีเมลถึงผู้ใช้ 101: ยืนยันการสั่งซื้อของคุณ
2. การใช้ Type Hints ขั้นสูงกับคลาส
Type Hints ใน Python พัฒนาอย่างมาก ช่วยลดข้อผิดพลาดและเพิ่มความเข้าใจในโค้ด
from typing import Generic, TypeVar, List, Optional
T = TypeVar('T')
class Repository(Generic[T]):
"""คลาส Generic สำหรับจัดการข้อมูลประเภทต่างๆ"""
def __init__(self):
self._items: List[T] = []
def add(self, item: T) -> None:
self._items.append(item)
def get_by_id(self, item_id: int) -> Optional[T]:
for item in self._items:
if getattr(item, 'id', None) == item_id:
return item
return None
def get_all(self) -> List[T]:
return self._items[:]
# การใช้งานกับคลาส Product จากตัวอย่างก่อนหน้า
product_repo = Repository[Product]()
product_repo.add(iphone)
product_repo.add(macbook)
found_product = product_repo.get_by_id(101)
if found_product:
print(f"พบสินค้า: {found_product.name}")
เปรียบเทียบ: Class-based Design vs Functional Design
| ด้านที่เปรียบเทียบ | Class-based Design (OOP) | Functional Design |
|---|---|---|
| แนวคิดหลัก | จัดกลุ่มข้อมูลและพฤติกรรมที่เกี่ยวข้องกันเป็นวัตถุ | เน้นการใช้ฟังก์ชันบริสุทธิ์ (Pure Functions) และการเปลี่ยนแปลงสถานะให้น้อยที่สุด |
| สถานะ (State) | สถานะถูกเก็บในวัตถุ (ผ่าน attributes) | หลีกเลี่ยงสถานะที่เปลี่ยนแปลงได้ (Mutable State) |
| ความยืดหยุ่น | ดีสำหรับการสร้างระบบที่ซับซ้อน มีความสัมพันธ์ระหว่างวัตถุ | ดีสำหรับการประมวลผลข้อมูลแบบ Pipeline หรือ Transformation |
| การทดสอบ | อาจทดสอบยากหากมีการพึ่งพาสถานะมาก | ทดสอบง่ายเนื่องจากฟังก์ชันบริสุทธิ์ให้ผลลัพธ์เดิมเมื่อรับอินพุตเดิม |
| เหมาะกับ | ระบบที่มีโครงสร้างชัดเจน (GUI, Game Entities, Business Domain Models) | Data Processing, Scientific Computing, Concurrent Programming |
| ใน Python | ใช้คลาส สืบทอด Polymorphism | ใช้ Higher-order Functions, Lambda, map/filter/reduce |
ในทางปฏิบัติ โปรเจกต์ Python สมัยใหม่มักใช้ทั้งสองกระบวนทัศน์ร่วมกัน (Hybrid Approach) อย่างเหมาะสม
Summary
Class ใน Python เป็นรากฐานที่ทรงพลังของการเขียนโปรแกรมเชิงวัตถุ ซึ่งช่วยให้นักพัฒนาสามารถสร้างซอฟต์แวร์ที่ซับซ้อนได้อย่างเป็นระบบ มีโครงสร้าง และบำรุงรักษาได้ง่าย จากการเรียนรู้ในคู่มือฉบับสมบูรณ์ปี 2026 นี้ เราได้เห็นตั้งแต่พื้นฐานของการประกาศคลาส การใช้งาน Attributes และ Methods หลากหลายประเภท ไปจนถึงการประยุกต์ใช้หลักการสำคัญของ OOP ทั้งสี่ข้ออย่างลึกซึ้ง พร้อมทั้งได้ศึกษากรณีศึกษาและ Best Practices ที่ทันสมัย การเข้าใจคลาสไม่ใช่แค่การเขียนโค้ดตาม syntax แต่คือการออกแบบโครงสร้างของความคิดให้สอดคล้องกับปัญหาจริง การเลือกใช้คลาสอย่างเหมาะสมร่วมกับแนวคิดการเขียนโปรแกรมแบบอื่นๆ จะทำให้คุณเป็นนักพัฒนาที่ครบเครื่อง สามารถสร้างสรรค์ผลงานที่มีคุณภาพและตอบโจทย์ความต้องการในโลกเทคโนโลยีที่เปลี่ยนแปลงอย่างรวดเร็วได้อย่างมีประสิทธิภาพ