H.Bukhari
H.Bukhari

Reputation: 2261

Constraint in Python @property setter not applied

I have pretty simple class, which converts temperature to Fahrenheit, in additional it makes sure that value are larger than -273

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

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

    @property
    def temperature(self):
        print('Getting_value')
        return self._temperature


    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("Temperature below -273 is not possible")
        print("Setting value")
        self._temperature = value

if I run following code

c = Celsius()
c.temperature=23
c.to_fahrenheit()

I get expected Output:

Setting value
Getting_value
Out[89]:
73.4

now trying to set up temperature to -275, we get error as expected!

c = Celsius()
c.temperature=-275
c.to_fahrenheit()

--------------------------------------------------------------------------- ValueError Traceback (most recent call last) in () 1 c = Celsius() ----> 2 c.temperature=-275 3 c.to_fahrenheit()

in temperature(self, value) 15 def temperature(self, value): 16 if value < -273: ---> 17 raise ValueError("Temperature below -273 is not possible") 18 print("Setting value") 19 self._temperature = value

ValueError: Temperature below -273 is not possible

so far so good! But problem is if I try to set up temperature during initiation of the class I can choose -275 and it will not prompt error

c = Celsius(-275)
c.to_fahrenheit()

> Getting_value Out[88]:
> -463.0

My question is why its not triggering error ? As I understood @temperature.setter will make sure to check if temperature is <-273 but for some reason it passes it.

Upvotes: 2

Views: 932

Answers (2)

Mr Alihoseiny
Mr Alihoseiny

Reputation: 1229

Because you did not call the property, instead you've called the private attribute. You should change constructor of your class to it:

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

Now when you initiate your class, the property will use and in bad input you will get the exception.

Upvotes: 0

Dmitry Shepelev
Dmitry Shepelev

Reputation: 152

It's happened because you use in init method

self._temperature = temperature

And your temperature setter don't execute. You can change your code to

self.temperature = temperature

It will execute temperature setter method and raise Exception.

Upvotes: 5

Related Questions