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

Truy cập thuộc tính class trong Python

Class object hỗ trợ hai thao tác: attribute reference (truy cập thuộc tính) và instantiation (tạo instance).

Attribute reference dùng cú pháp chuẩn obj.name. Tên thuộc tính hợp lệ là tất cả tên trong namespace của class khi tạo class object.

Ví dụ

class MyClass:
    \"\"\"A simple example class\"\"\"
    i = 12345
    
    def f(self):
        return 'hello world'

# Truy cập class attribute
print(MyClass.i)    # 12345
print(MyClass.f)    # 
print(MyClass.__doc__)  # A simple example class

# Gán giá trị mới cho class attribute
MyClass.i = 999
print(MyClass.i)    # 999

Lưu ý: Gán MyClass.i = 999 thay đổi class attribute. Gán instance.i = 999 tạo instance attribute mới, che khuất class attribute.