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

Python là hướng đối tượng hay thủ tục?

Python hỗ trợ cả hai: lập trình hướng đối tượng (OOP) và lập trình thủ tục (procedural). Là ngôn ngữ đa paradigm (multi-paradigm), Python cho phép viết code theo phong cách OOP, thủ tục, hay hàm (functional).

Đặc điểm OOP trong Python

  • Class & Object
  • Encapsulation (đóng gói)
  • Inheritance (kế thừa)
  • Polymorphism (đa hình)

Ví dụ OOP: Lớp Rectangle

class Rectangle:
    def __init__(self, length, breadth, unit_cost=0):
        self.length = length
        self.breadth = breadth
        self.unit_cost = unit_cost
    
    def get_perimeter(self):
        return 2 * (self.length + self.breadth)
    
    def get_area(self):
        return self.length * self.breadth
    
    def calculate_cost(self):
        area = self.get_area()
        return area * self.unit_cost

# breadth = 120 cm, length = 160 cm, 1 cm^2 = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s cm^2" % r.get_area())
print("Cost of rectangular field: Rs. %s" % r.calculate_cost())
Area of Rectangle: 19200 cm^2
Cost of rectangular field: Rs. 38400000

Lập trình thủ tục trong Python

Dùng hàm, vòng lặp (for, while), cấu trúc điều khiển (if/else) mà không cần class:

def tinh_tien(dai, rong, don_gia):
    dien_tich = dai * rong
    return dien_tich * don_gia

print("Chi phí:", tinh_tien(160, 120, 2000))

Tóm lại

Python không ép buộc phong cách nào. Bạn chọn OOP khi cần mô hình hóa thực thể phức tạp, kế thừa, đa hình; chọn thủ tục cho script đơn giản, xử lý dữ liệu tuyến tính.