Skip to content
Foxipa
Code Completion 6 Challenges

Complete the Python Special Methods Code

Practice connecting built-in operations and formatted output to special methods on your own classes.

~10 min read

Challenge 1

Make repr(box) show Box(3) by defining the representation method.

python Your answer
class Box:
    def __init__(self, size):
        self.size = size

    

box = Box(3)
print(repr(box))

Press Ctrl⌘Enter to check your answer

Challenge 2

Make len(queue) return the number of queued items.

python Your answer
class Queue:
    def __init__(self, items):
        self.items = list(items)

    

queue = Queue(["a", "b", "c"])
print(len(queue))

Press Ctrl⌘Enter to check your answer

Challenge 3

Make membership tests use the stored names set.

python Your answer
class Tags:
    def __init__(self, names):
        self.names = set(names)

    

tags = Tags(["python", "html"])
print("python" in tags)

Press Ctrl⌘Enter to check your answer

Challenge 4

Make two Score objects add their points when + is used.

python Your answer
class Score:
    def __init__(self, points):
        self.points = points

    

a = Score(8)
b = Score(5)
result = a + b
print(result.points)

Press Ctrl⌘Enter to check your answer

Challenge 5

Make f"{price:currency}" return "$12.50", while forwarding every other format specification to the stored amount.

python Your answer
class Price:
    def __init__(self, amount):
        self.amount = amount

    

price = Price(12.5)
print(f"{price:currency}")
print(f"{price:.1f}")

Press Ctrl⌘Enter to check your answer

Challenge 6

Make bytes(packet) return the two-byte record b'\x02\x0f'.

python Your answer
class StatusPacket:
    def __init__(self, status, value):
        self.status = status
        self.value = value

    

packet = StatusPacket(2, 15)
print(bytes(packet))

Press Ctrl⌘Enter to check your answer