Complete the code to define a magic method that returns a string representation of an object.
class Book: def __init__(self, title): self.title = title def [1](self): return f"Book: {self.title}"
The __str__ method is a magic method that returns a readable string representation of an object.
Complete the code to define a magic method that allows adding two objects of the class.
class Number: def __init__(self, value): self.value = value def [1](self, other): return Number(self.value + other.value)
The __add__ magic method lets you define how the + operator works for your objects.
Fix the error in the magic method that compares two objects for equality.
class Person: def __init__(self, name): self.name = name def [1](self, other): return self.name == other.name
The __eq__ method defines how two objects are compared using ==.
Fill both blanks to create a magic method that returns the length of a custom container.
class CustomList: def __init__(self, items): self.items = items def [1](self): return [2]
The __len__ method returns the number of items in the container. Using len(self.items) gets the length of the internal list.
Fill all three blanks to create a magic method that allows indexing into a custom container.
class CustomList: def __init__(self, items): self.items = items def [1](self, [2]): return [3]
The __getitem__ method allows using square brackets to access elements. It takes an index and returns the item at that position.