Addition of two classes gives TypeError

Viewed 34

I have defined a class that returns the temperature.

class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def _add_(self,other):
        return Celsius(self.temperature + other.temperature)

    @property
    def temperature(self):
        print("Getting value...")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        print("Setting value...")
        self._temperature = value
        
print("my temperature is :",Celsius(37).temperature)

What do I need to do if I want to add the temperature of two classes? If I type: temp_total = Celsius(37) + Celsius(6) It gives me a TypeError. I thought I could solve this with the '__ add __' expression, but this does not work. Any idea?

I want to type out = Celsius(37) + Celsius(6) to give me out.temperature = 43.

1 Answers

Yes, you need the __add__ function to override the sum operation, if not, Python will try to add both objects without result because they are not built-in data types:

class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    @property
    def temperature(self):
        print("Getting value...")
        return self._temperature

    @temperature.setter
    def temperature(self, value):
        print("Setting value...")
        self._temperature = value
    
    def __add__(self, other):
        return Celsius(self.temperature+other.temperature)
        
print((Celsius(3)+Celsius(3)).temperature)

Output:

Setting value...
Setting value...
Getting value...
Getting value...
Setting value...
Getting value...
6
Related