Editor

Slots with Inheritance

Advanced · Write the code · from Python __slots__: Reduce Memory Usage by 40%

From the lesson: Python __slots__: Reduce Memory Usage by 40%

Imagine a parking lot. A normal Python object is like an open field where cars can park anywhere. Flexible, but wasteful - you need a huge space even if only a few cars show up.

Read the lesson

Create a base class Shape with __slots__ = ('name',) and an __init__ that sets self.name. Then create a child class Circle that adds a radius slot. Its __init__ should take radius, call super().__init__('Circle'), and set self.radius. Create a Circle with radius 5, then print its name and radius on separate lines.

# Create Shape base class with __slots__
# Create Circle child class with its own __slots__
# Create a Circle and print name and radius

More __slots__ exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz