0
0
Pythonprogramming~20 mins

Purpose of magic methods in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Magic Methods Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this code using __str__ magic method?
Consider the following Python class with a magic method. What will be printed when the code runs?
Python
class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return f"Book title: {self.title}"

b = Book("Python Basics")
print(b)
A<__main__.Book object at 0x...>
BBook title: Python Basics
CPython Basics
DError: __str__ method missing
Attempts:
2 left
💡 Hint
The __str__ method controls what print shows for an object.
Predict Output
intermediate
2:00remaining
What does this code print using __len__ magic method?
Look at this class with a __len__ method. What will print when len(obj) is called?
Python
class Basket:
    def __init__(self, items):
        self.items = items
    def __len__(self):
        return len(self.items)

obj = Basket(['apple', 'banana', 'cherry'])
print(len(obj))
A0
BError: __len__ method not found
C['apple', 'banana', 'cherry']
D3
Attempts:
2 left
💡 Hint
The __len__ method tells Python how to get the length of an object.
🧠 Conceptual
advanced
2:00remaining
Why use magic methods like __add__ in classes?
What is the main purpose of defining magic methods such as __add__ in a Python class?
ATo prevent the class from being instantiated
BTo make the class run faster
CTo allow objects of the class to use operators like + in a custom way
DTo automatically generate documentation for the class
Attempts:
2 left
💡 Hint
Think about what happens when you use + between two objects.
Predict Output
advanced
2:00remaining
What error does this code raise without __eq__ magic method?
What happens when you compare two objects of this class without defining __eq__?
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p1 = Point(1, 2)
p2 = Point(1, 2)
print(p1 == p2)
AFalse
BTrue
CTypeError
DSyntaxError
Attempts:
2 left
💡 Hint
Without __eq__, == compares object identity, not content.
🧠 Conceptual
expert
2:00remaining
Which magic method allows an object to be used as a context manager?
To use an object with the 'with' statement, which magic methods must the class implement?
A__enter__ and __exit__
B__init__ and __del__
C__call__ and __repr__
D__str__ and __len__
Attempts:
2 left
💡 Hint
The 'with' statement needs special methods to start and end the block.