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

Method constructor __init__ trong Python hoạt động như thế nào?

__init__

__init__ là reserved method trong Python class. Gọi là constructor trong OOP. Được gọi khi object tạo từ class, cho phép khởi tạo attribute của class.

Cách sử dụng

class Car:
    def __init__(self, model, color, speed):
        self.color = color
        self.speed = speed
        self.model = model
    
    def start(self):
        print("started")
    
    def accelerate(self):
        print("accelerating...")
    
    def change_gear(self, gear_type):
        print("gear changed")

# Tạo instance - tự động gọi __init__
my_car = Car("Toyota", "Red", 0)
my_car.start()  # started

Điểm quan trọng: __init__ không trả về giá trị (return None). Nó khởi tạo instance đã được tạo bởi __new__.