Summary - Magic methods
- Python course
- Intermediate
- Lesson 35/116
- 5 min
Combine __eq__, __add__ and __iter__ to write a Vector class.
Summary - Magic methods
In this group we covered __eq__, __lt__, __add__, __len__, __getitem__, __iter__, __next__ and __contains__. These let class instances work with built-in operators.
Define __eq__ for ==, __add__ for +, __len__ for len(), __contains__ for in. Now we'll combine these into a Number class.
Practice Combine the Number class
Define the Number class. Add def __init__(self, value): with self.value = value in the body. Add def __eq__(self, other): with return self.value == other.value. Add def __add__(self, other): with return Number(self.value + other.value). Then call n1 = Number(5), n2 = Number(5), print(n1 == n2), n3 = n1 + Number(3) and print(n3.value).
Starter code
# Combine the Number classSample solution
# Combine the Number class
class Number:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __add__(self, other):
return Number(self.value + other.value)
n1 = Number(5)
n2 = Number(5)
print(n1 == n2)
n3 = n1 + Number(3)
print(n3.value)Expected output
True 8
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which method does the + operator call?
- self
- __add__ Correct answer
- this
- class
Explanation: The + operator calls the __add__ method.
2 Match the concepts
| Term | Meaning |
|---|---|
__eq__ |
== operator |
__add__ |
+ operator |
__len__ |
len() |
3 Complete the __add__ body
class Number:
def __init__(self, value):
self.____ = value
class Number:
def __init__(self, value):
self.value = value
Explanation: The value parameter is assigned to self.value.