Python การใช้งาน Class และ Object

ใน Python การใช้งาน Class และ Object เป็นพื้นฐานสำคัญของการเขียนโปรแกรมเชิงวัตถุ (Object-Oriented Programming: OOP) โดย Class เปรียบเสมือนพิมพ์เขียวที่ใช้สร้าง Object และ Object คือสิ่งที่สร้างขึ้นจาก Class เพื่อใช้งานในโปรแกรม

Class (คลาส)

  • Class คือแม่แบบ (Template) หรือพิมพ์เขียวในการสร้าง Object ซึ่งจะกำหนดคุณสมบัติ (Attribute) และพฤติกรรม (Method) ของ Object นั้น ๆ
  • การประกาศ Class ใช้คีย์เวิร์ด class ตามด้วยชื่อ Class

ตัวอย่างการสร้าง Class

Python
class Car:
    # ตัวแปร (Attribute) ของคลาส
    wheels = 4
    
    # ตัวสร้าง (Constructor) สำหรับการสร้างวัตถุใหม่
    def __init__(self, color, brand):
        self.color = color  # คุณสมบัติของวัตถุ
        self.brand = brand

    # ฟังก์ชัน (Method) ของคลาส
    def start_engine(self):
        return f"{self.brand} car's engine started."

    def stop_engine(self):
        return f"{self.brand} car's engine stopped."

ในตัวอย่างนี้ Class Car มีตัวแปรประจำคลาส wheels และฟังก์ชันสองฟังก์ชันคือ start_engine และ stop_engine รวมถึงมีตัวสร้าง __init__ ที่กำหนดคุณสมบัติของ Object เช่น color และ brand

Object (วัตถุ)

  • Object คืออินสแตนซ์ (Instance) หรือการใช้งานจริงของ Class เมื่อเราเรียก Class เพื่อสร้าง Object
  • เราสามารถสร้าง Object จาก Class ได้โดยการเรียกชื่อ Class พร้อมใส่ข้อมูลลงไป

ตัวอย่างการสร้าง Object

Python
# สร้างวัตถุจากคลาส Car
my_car = Car("Red", "Toyota")

print(my_car.color)  # Output: Red
print(my_car.brand)  # Output: Toyota

# เรียกใช้ฟังก์ชันในคลาส Car ผ่านวัตถุ
print(my_car.start_engine())  # Output: Toyota car's engine started.
print(my_car.stop_engine())   # Output: Toyota car's engine stopped.

ในตัวอย่างนี้ my_car เป็น Object ที่สร้างจาก Class Car และเราสามารถเข้าถึงคุณสมบัติและฟังก์ชันของมันได้

การประยุกต์ใช้งาน Class และ Object รูปแบบต่าง ๆ

Inheritance (การสืบทอดคลาส)

  • การสืบทอดคือการสร้าง Class ใหม่โดยใช้คุณสมบัติและพฤติกรรมจาก Class ที่มีอยู่เดิม
Python
class ElectricCar(Car):  # คลาส ElectricCar สืบทอดจาก Car
    def __init__(self, color, brand, battery_capacity):
        super().__init__(color, brand)  # เรียกใช้ตัวสร้างของคลาส Car
        self.battery_capacity = battery_capacity  # คุณสมบัติเพิ่มเติมของ ElectricCar

    def charge_battery(self):
        return f"{self.brand} car's battery is charging."

# สร้างวัตถุจากคลาส ElectricCar
my_electric_car = ElectricCar("Blue", "Tesla", "100 kWh")

print(my_electric_car.start_engine())  # Output: Tesla car's engine started.
print(my_electric_car.charge_battery())  # Output: Tesla car's battery is charging.

ในตัวอย่างนี้ คลาส ElectricCar สืบทอดจากคลาส Car โดยมีคุณสมบัติเพิ่มเติมคือ battery_capacity และฟังก์ชันใหม่ charge_battery

Polymorphism (ความหลายรูป)

  • Polymorphism หมายถึงการที่เราสามารถใช้เมธอดเดียวกันแต่ทำงานแตกต่างกันในคลาสที่ต่างกัน
Python
class Dog:
    def sound(self):
        return "Woof!"

class Cat:
    def sound(self):
        return "Meow!"

def animal_sound(animal):
    print(animal.sound())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!

ในตัวอย่างนี้ ฟังก์ชัน animal_sound สามารถรับวัตถุจากคลาสที่แตกต่างกันได้ และเรียกใช้เมธอด sound ที่แต่ละคลาสมีการนิยามไว้

Encapsulation (การห่อหุ้มข้อมูล)

  • Encapsulation คือการซ่อนรายละเอียดภายในคลาสและเปิดเผยเฉพาะสิ่งที่จำเป็น
Python
class BankAccount:
    def __init__(self, owner, balance):
        self.owner = owner
        self.__balance = balance  # ตัวแปรส่วนตัว (Private)

    def deposit(self, amount):
        self.__balance += amount

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount
        else:
            return "Insufficient funds"

    def get_balance(self):
        return self.__balance

# สร้างวัตถุจากคลาส BankAccount
account = BankAccount("John", 1000)
account.deposit(500)
account.withdraw(300)
print(account.get_balance())  # Output: 1200

ในตัวอย่างนี้ __balance เป็นตัวแปรส่วนตัว (Private) ที่ไม่สามารถเข้าถึงได้จากภายนอกโดยตรง ต้องใช้เมธอด get_balance ในการตรวจสอบ

Abstraction

  • Abstraction คือการซ่อนรายละเอียดการทำงานที่ซับซ้อน และเปิดเผยเฉพาะส่วนที่จำเป็นต่อการใช้งาน
Python
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def sound(self):
        pass

class Dog(Animal):
    def sound(self):
        return "Woof!"

class Cat(Animal):
    def sound(self):
        return "Meow!"

# สร้างวัตถุจากคลาสที่สืบทอด
dog = Dog()
cat = Cat()

print(dog.sound())  # Output: Woof!
print(cat.sound())  # Output: Meow!

ในตัวอย่างนี้ คลาส Animal เป็นคลาสนามธรรมที่มีเมธอด sound เป็นนามธรรม (Abstract) และคลาสลูกจะต้องกำหนดวิธีทำงานของเมธอดนี้

สรุป

การใช้ Class และ Object ใน Python เป็นพื้นฐานสำคัญของการเขียนโปรแกรมเชิงวัตถุ ซึ่งมีแนวคิดหลายรูปแบบที่สามารถนำไปประยุกต์ใช้งานได้ เช่น การสืบทอด (Inheritance), ความหลายรูป (Polymorphism), การห่อหุ้มข้อมูล (Encapsulation) และ Abstraction

อ่านเพิ่มเติม

แชร์เรื่องนี้