Question:
Using Magic Methods, overload the + operator so that length of varying units can be added.
Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
class Length: __metric = {"mm" : 0.001, "cm" : 0.01, "m" : 1, "km" : 1000, "in" : 0.0254, "ft" : 0.3048, "yd" : 0.9144, "mi" : 1609.344 } def __init__(self, value, unit = "m" ): self.value = value self.unit = unit def Converse2Metres(self): return self.value * Length.__metric[self.unit] def __add__(self, other): l = self.Converse2Metres() + other.Converse2Metres() return Length(l / Length.__metric[self.unit], self.unit ) def __str__(self): return str(self.Converse2Metres()) def __repr__(self): return "Length(" + str(self.value) + ", '" + self.unit + "')" if __name__ == "__main__": x = Length(4) print(x) y = eval(repr(x)) z = Length(7.9, "yd") + Length(2) print(repr(z)) print(z) |
Explanation:
What are magic methods? They’re everything in object-oriented Python. They’re special methods that you can define to add “magic” to your classes, that is you won’t have to call them manually. They are called automatically behind the scenes.
Output:
1 2 3 |
4 Length(10.0872265967, 'yd') 9.22376 |
Leave a Reply