Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Object-Oriented Programming ใน Python (OOP)

Python เป็นภาษา Object-Oriented ตั้งแต่แรกเริ่ม Class และ Object เป็นสอง Building Blocks หลักของ OOP

กำหนด Class ใน Python

# Class พื้นฐาน
class Vehicle:
    pass  # Empty Class

# สร้าง Object (Instantiate)
v = Vehicle()
print(v)  # <__main__.Vehicle object at 0x...>

เพิ่ม Method ใน Class

class Vehicle:
    def car(self):
        color = 'Red'
        return color

v = Vehicle()
print(v.car())  # Red
print(v)

Instance Methods และ self

ใน Python เมธอดใน Class ต้องมีพารามิเตอร์แรกเป็น self (อ้างอิงถึง Instance เอง) เมื่อเรียกผ่าน Instance ไม่ต้องส่ง self เอง Python จะส่งให้อัตโนมัติ

class MyClass:
    def my_method(self):
        return 'Hello'

obj = MyClass()
print(obj.my_method())  # Hello - ไม่ต้องส่ง self

หากลืม self จะเกิด Error:

TypeError: my_method() takes 0 positional arguments but 1 was given

Instance Attributes

Attributes ที่เฉพาะเจาะจงต่อ Instance แต่ละตัว กำหนดใน __init__

import random

class MyClass:
    def set_random(self):
        self.attrib1 = random.randint(1, 11)
        self.attrib2 = random.randint(1, 21)

obj = MyClass()
obj.set_random()
print(obj.attrib1, obj.attrib2)

__init__ Constructor

Constructor ใช้ Initialize Instance Attributes เมื่อสร้าง Object Python เรียก __init__ อัตโนมัติ

class Employee:
    def __init__(self, name):
        self.name = name
    
    def display(self):
        print("Employee name:", self.name)

obj1 = Employee('Zack')
obj2 = Employee('Rajesh')
obj3 = Employee('Tashleem')

obj3.display()  # Employee name: Tashleem
obj1.display()  # Employee name: Zack

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

Python ใช้ Naming Convention สำหรับ Access Control:

  • public_attr: Public (เข้าถึงได้ทุกที่)
  • _protected_attr: Protected (โดยสัญญา - ใช้ภายใน Class/Subclass)
  • __private_attr: Private (Name Mangling - _ClassName__attr)
class Product:
    def __init__(self):
        self.__max_price = 1000   # Private
        self.__min_price = 1      # Private
    
    def selling_price(self):
        print(f'Max: {self.__max_price}, Min: {self.__min_price}')
    
    def set_max_price(self, price):
        self.__max_price = price
    
    def set_min_price(self, price):
        self.__min_price = price

prod = Product()
prod.selling_price()           # Max: 1000, Min: 1
prod.__max_price = 1500        # สร้าง Attribute ใหม่ ไม่เปลี่ยน Private
prod.selling_price()           # Max: 1000, Min: 1 (ยังค่าเดิม)
prod.set_max_price(1500)       # ต้องใช้ Method
prod.selling_price()           # Max: 1500, Min: 1

Inheritance และ Polymorphism

class Animal:
    def speak(self):
        print("Animal sound")

class Dog(Animal):
    def speak(self):           # Override
        print("Woof!")

class Cat(Animal):
    def speak(self):           # Override
        print("Meow!")

animals = [Dog(), Cat()]
for a in animals:
    a.speak()                  # Polymorphism

สรุป OOP ใน Python

ConceptPython Syntax
Classclass Name:
Constructordef __init__(self, ...):
Instance Methoddef method(self, ...):
Class Method@classmethod def method(cls, ...):
Static Method@staticmethod def method(...):
Private Attrself.__attr
Inheritanceclass Child(Parent):
Super Callsuper().__init__()