__slots__ variable in Python classes

PHOTO EMBED

Tue Jun 18 2024 16:44:52 GMT+0000 (Coordinated Universal Time)

Saved by @pynerds #python

class Point:
    __slots__ = ('x', 'y')
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)
print(f'x: {p.x}')
print(f'y: {p.y}')
content_copyCOPY

__slots__ is a special class variable in Python that restricts the attributes that can be assigned to an instance of a class. If __slots__ is defined, an exception will be raised if an attribute that is not in the list is assigned to an instance.

https://www.pynerds.com/slots-variable-in-python-classes/