Slots Optimization in Python

Level 4158 keystrokes

This uses __slots__ to optimize memory usage. Slots prevent creation of __dict__ and limit attributes to those specified.

Python code

# Define class with __slots__ for memory optimization
1class Point:
# __slots__ defines allowed attributes
2 __slots__ = ['x', 'y']
3
# Initialize with x and y coordinates
4 def __init__(self, x, y):
# Set x attribute
5 self.x = x
# Set y attribute
6 self.y = y
7
# Create Point instance with coordinates (3, 4)
8p = Point(3, 4)
# Print the coordinates using f-string
9print(f"x={p.x}, y={p.y}")
# __slots__ means instances have no __dict__, so this prints False
10print(hasattr(p, '__dict__'))

Output

x=3, y=4
False
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • _× 12
  • ,× 6
  • '× 6
  • =× 6
  • (× 5
  • )× 5
  • .× 4
  • :× 2
  • "× 2
  • {× 2

More Python examples at level 4

← Python typing practice