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

self trong lớp Python

Trong hướng dẫn này, chúng ta tìm hiểu self trong Python.

Lưu ý: self KHÔNG phải từ khóa trong Python.

self dùng trong lớp để đại diện cho instance của object. Mỗi instance có giá trị thuộc tính khác nhau, self giúp truy cập thuộc tính/phương thức của instance đó.

Ví dụ cơ bản

class Laptop:
    def __init__(self, company, model):
        self.company = company
        self.model = model

laptop_one = Laptop('Lenovo', 'ideapad320')
laptop_two = Laptop('Dell', 'inspiron 7000')
print(f"Laptop One: {laptop_one.company}")
print(f"Laptop Two: {laptop_two.company}")

Kết quả

Laptop One: Lenovo
Laptop Two: Dell

Python tự động truyền tham chiếu instance vào self khi gọi phương thức. self không phải từ khóa, có thể đổi tên (nhưng khuyến nghị dùng self).

Ví dụ đổi tên self

class Laptop:
    def __init__(other_than_self, company, model, colors):
        other_than_self.company = company
        other_than_self.model = model
        other_than_self.colors_available = colors
    def is_laptop_available(not_self_but_still_self, color):
        return color in not_self_but_still_self.colors_available

laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])
print("Available" if laptop.is_laptop_available('Silver') else "Not available")
print("Available" if laptop.is_laptop_available('White') else "Not available")

Kết quả

Available
Not available

Kết luận

self là tham số thứ nhất của phương thức instance, Python tự truyền reference. Quy ước dùng 'self'. Hãy bình luận nếu có thắc mắc.