0
0
Pythonprogramming~10 mins

Purpose of magic methods in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a magic method that returns a string representation of an object.

Python
class Book:
    def __init__(self, title):
        self.title = title
    def [1](self):
        return f"Book: {self.title}"
Drag options to blanks, or click blank then click option'
A__call__
B__str__
C__repr__
D__init__
Attempts:
3 left
💡 Hint
Common Mistakes
Using __init__ instead of __str__
Confusing __repr__ with __str__
Forgetting to return a string
2fill in blank
medium

Complete the code to define a magic method that allows adding two objects of the class.

Python
class Number:
    def __init__(self, value):
        self.value = value
    def [1](self, other):
        return Number(self.value + other.value)
Drag options to blanks, or click blank then click option'
A__mul__
B__sub__
C__add__
D__eq__
Attempts:
3 left
💡 Hint
Common Mistakes
Using __sub__ instead of __add__
Not returning a new object
Forgetting the second parameter
3fill in blank
hard

Fix the error in the magic method that compares two objects for equality.

Python
class Person:
    def __init__(self, name):
        self.name = name
    def [1](self, other):
        return self.name == other.name
Drag options to blanks, or click blank then click option'
A__eq__
B__lt__
C__str__
D__init__
Attempts:
3 left
💡 Hint
Common Mistakes
Using __lt__ which is for less than comparison
Using __str__ which returns string representation
Not defining the method at all
4fill in blank
hard

Fill both blanks to create a magic method that returns the length of a custom container.

Python
class CustomList:
    def __init__(self, items):
        self.items = items
    def [1](self):
        return [2]
Drag options to blanks, or click blank then click option'
A__len__
Blen(self.items)
Cself.items
Dself.length
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the list itself instead of its length
Using wrong method name
Not returning anything
5fill in blank
hard

Fill all three blanks to create a magic method that allows indexing into a custom container.

Python
class CustomList:
    def __init__(self, items):
        self.items = items
    def [1](self, [2]):
        return [3]
Drag options to blanks, or click blank then click option'
A__getitem__
Bindex
Cself.items[index]
Dself.items
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method name
Forgetting the index parameter
Returning the whole list instead of one item