Nâng CaoPython iconPython

`__slots__` là gì? Khi nào nên dùng?

__slots__ giới hạn attributes của instance, loại bỏ __dict__ — tiết kiệm bộ nhớ ~40-60% khi có nhiều instances.

python
class PointNormal:
    def __init__(self, x, y):
        self.x, self.y = x, y
# Mỗi instance có __dict__ → ~200 bytes

class PointSlots:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x, self.y = x, y
# Không có __dict__ → ~56 bytes

# p = PointSlots(1, 2)
# p.z = 3  # AttributeError — không thể thêm attribute mới

Dùng khi: tạo hàng triệu instances nhỏ (data processing, game objects, ML features).

Xem toàn bộ Python cùng filter theo level & chủ đề con.

Mở danh sách Python