__slots__
- Python course
- Intermediate
- Lesson 22/116
- 4 min
Learn memory savings with __slots__.
The __slots__ attribute
__slots__ restricts the attribute names a class can have, given as a tuple. This saves memory and prevents accidental new attributes.
Example: class Point:\n __slots__ = ("x", "y"). Now p.x and p.y can be set; writing p.z = 3 raises AttributeError. This strengthens encapsulation; the class layout stays fixed. When many instances are created, the memory saving becomes meaningful.
Memory and layout
Classes that use __slots__ do not carry a __dict__ per instance; this reduces the memory footprint. With thousands of instances, the difference is clear.
Example: class Point:\n __slots__ = ("x", "y")\n def __init__(self, x, y):\n self.x = x\n self.y = y. The instance p = Point(3, 4) carries only x and y. Writing p.z = 5 raises an error. The layout is fixed; new names cannot be added.
Practice Add __slots__ to Point
Define a class named Point. Add __slots__ = ("x", "y") in the body. Add the method def __init__(self, x, y): and in the body write self.x = x and self.y = y. Then create an instance with p = Point(3, 4) and call print(p.x + p.y).
Starter code
# Define the Point class with __slots__Sample solution
# Define the Point class with __slots__
class Point:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(3, 4)
print(p.x + p.y)Expected output
7
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the __slots__ concepts
| Term | Meaning |
|---|---|
__slots__ |
Attribute limit |
("x", "y") |
Allowed names |
AttributeError |
New name blocked |
2 What does __slots__ do?
- It adds new methods
- It limits the attribute set Correct answer
- It deletes the class
- It removes class variables
Explanation: __slots__ allows only the listed names to be used.
3 Complete the __slots__ declaration
class Point:
____ = ("x", "y")
class Point:
__slots__ = ("x", "y")
Explanation: __slots__ starts and ends with two underscores.