Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Lập trình hướng đối tượng (OOP) trong Python

Python là ngôn ngữ hướng đối tượng (OOP) ngay từ đầu. Hai khối xây dựng chính: Class (lớp) và Object (đối tượng/instance).

Định nghĩa Class

class Vehicle:
    pass  # Class rỗng

v = Vehicle()
print(v)  # <__main__.Vehicle object at 0x...>

Phương thức instance (Instance Methods)

Phương thức đầu tiên luôn là self (tham chiếu đến instance).

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

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

Constructor __init__

Khởi tạo attribute cho instance. Được gọi tự động khi tạo object.

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

obj1 = Employee('Zack')
obj2 = Employee('Rajesh')
obj1.display()  # Employee name: Zack
obj2.display()  # Employee name: Rajesh

Instance Attributes (Thuộc tính instance)

Mỗi object có bản sao riêng của attribute.

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)

Encapsulation (Đóng gói)

Python dùng convention: _name (protected), __name (private - name mangling).

class Product:
    def __init__(self):
        self.__maxprice = 1000   # private (name mangling -> _Product__maxprice)
        self.__minprice = 1
    
    def selling_price(self):
        print(f'Max: {self.__maxprice}, Min: {self.__minprice}')
    
    def set_max_price(self, price):
        self.__maxprice = price
    
    def set_min_price(self, price):
        self.__minprice = price

p = Product()
p.selling_price()           # Max: 1000, Min: 1
p.__maxprice = 1500         # Tạo attribute MỚI __maxprice (khác _Product__maxprice)
p.selling_price()           # Vẫn: Max: 1000, Min: 1
p.set_max_price(1500)       # Đúng cách
p.selling_price()           # Max: 1500, Min: 1

Kế thừa (Inheritance)

class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        pass

class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"

class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"

animals = [Dog('Buddy'), Cat('Whiskers')]
for a in animals:
    print(a.speak())
Buddy says Woof!
Whiskers says Meow!

Polymorphism (Đa hình)

Cùng interface speak(), hành vi khác nhau tùy class.

Magic Methods (Dunder methods)

MethodMục đích
__init__Khởi tạo
__str__String representation (print)
__repr__Official representation (debug)
__eq__So sánh ==
__len__len(obj)
__getitem__obj[key]
__call__obj()

Class Method & Static Method

class MyClass:
    count = 0
    
    def __init__(self):
        MyClass.count += 1
    
    @classmethod
    def get_count(cls):
        return cls.count
    
    @staticmethod
    def utility():
        return "Static method"

print(MyClass.get_count())  # 0
a = MyClass()
b = MyClass()
print(MyClass.get_count())  # 2