Skip to content
Foxipa
Code Completion 4 Challenges

Complete the Python __slots__ Code

Practice declaring slots, restricting attributes, allowing a dictionary explicitly, and using slots across inheritance.

Advanced ~8 min read

Challenge 1

Declare name and active as the only supported instance attributes.

python Your answer
class User:
    

user = User()
user.name = "Maya"
user.active = True
print(user.name, user.active)

Press Ctrl⌘Enter to check your answer

Challenge 2

Allow both the name slot and additional dynamic attributes.

python Your answer
class User:
    __slots__ = ("name", 

user = User()
user.name = "Maya"
user.color = "blue"
print(user.__dict__)

Press Ctrl⌘Enter to check your answer

Challenge 3

Give the child class its own extra slot while preserving the parent slot.

python Your answer
class Parent:
    __slots__ = ("name",)

class Child(Parent):
    

child = Child()
child.name = "Ada"
child.score = 100
print(child.name, child.score)

Press Ctrl⌘Enter to check your answer

Challenge 4

Declare only the count slot so the extra assignment raises AttributeError.

python Your answer
class Counter:
    

counter = Counter()
counter.count = 1
try:
    counter.label = "items"
except AttributeError:
    print("label not allowed")

Press Ctrl⌘Enter to check your answer