i trying fill gap in understanding of pythons property()
. below code have come with, understand property()
:
class temperature: def __init__(self, temp = 10): self.set_temp(temp) def to_farenheit(self): return (self._temp * 1.8) + 32 def get_temp(self): print "getting temperature value" return self._temp def set_temp(self, temp): print "setting temperature value" if temp < -237: raise valueerror("this shud above -273") else: self._temp = temp temps = property(get_temp, set_temp)
i execute above class , following:
>>> t = temperature() setting temperature value >>> t.temps getting temperature value 10 >>> t.temps = 13 >>> t.temps 13 >>> t.get_temp() getting temperature value 10 >>>
as can see above, when try set temp
value assigning t.temps = 13
set_temp()
function not getting called expecting called because of property()
functionality. ending 2 different values variable temp
what missing?
it's because use python 2 , forgot subclass object
. in case property
doesn't work because it's old-style class.
better subclass object
:
class temperature(object): ...
or better: use python 3. python 3 doesn't have old-style classes anymore , can omit (object)
part because it's implicit.
however shouldn't define get_temp
or set_temp
functions when use decorator syntax. , shouldn't call them directly.
this more pythonic:
class temperature(object): def __init__(self, temp = 10): self.temps = temp def to_farenheit(self): return (self._temp * 1.8) + 32 @property def temps(self): print("getting temperature value") return self._temp @temps.setter def temps(self, temp): print("setting temperature value") if temp < -237: raise valueerror("this shud above -273") else: self._temp = temp
that example work on python 2 and python 3.
Comments
Post a Comment