Module (7%)
Section (45%)

Pay attention to the fact that the __add__() method does not change any object attribute values – it just returns a value that is the result of adding the appropriate attribute values.

And in fact, the string class has its own implementation for the '+' operator, which is inherent to strings, different than implementations inherent to integers or floats.

When you design and implement your own classes and you want to make use of Python core syntax to operate on those class objects, you can easily achieve this by implementing the appropriate magic methods.


Code

class Person:
def __init__(self, weight, age, salary):
self.weight = weight
self.age = age
self.salary = salary

def __add__(self, other):
return self.weight + other.weight


p1 = Person(30, 40, 50)
p2 = Person(35, 45, 55)

print(p1 + p2)
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×