Editor

Fix the Bug: Missing Slot

Intermediate · Fix the bug · 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

This code defines a Student class with __slots__ but crashes when setting the grade attribute. Fix the __slots__ definition so all three attributes work. The output should print the student's name, age, and grade.

class Student:
__slots__ = ('name', 'age')
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
s = Student('Alice', 15, 'A')
print(f'{s.name}, age {s.age}, grade {s.grade}')

More __slots__ exercises

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