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

Khác biệt giữa self và __init__ trong Python class

self

self đại diện cho instance của class. Dùng từ khóa self để truy cập attribute và method của class trong Python.

__init__ method

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

Ví dụ

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

# breadth=120, length=160, cost=2000/sq unit
r = Rectangle(160, 120, 2000)
print("Area:", r.get_area(), "sq units")
print("Cost: Rs.", r.calculate_cost())

Kết quả

Area: 19200 sq units
Cost: Rs. 38400000

Tóm tắt: self = tham chiếu instance hiện tại. __init__ = method đặc biệt chạy khi tạo instance.