I was just experimenting with the property decorators when I figured out that a print statement from within a property setter would not always do its job, all other conditions equal. In the below example, I am getting the expected output from the directly initialized class instance (the fiver
section), but not when appending instances to a list (the objlist
section). Python 3.5.3
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("Guess, you know what you're doing...")
if value < -273:
print ("Impossible temperature...")
self._temperature = -273
else:
self._temperature = value
objlist=[]
objlist.append(Celsius(4))
objlist.append(Celsius(-499))
fiver=Celsius(5)
print (fiver.temperature)
fiver.temperature=-408
print (fiver.temperature)
In your __init__
you set the "internal" value _temperature
directly. This doesn't call the setter
, as the property.setter
is defined over temperature
.
If you want the __init__
to pass through the setter
validation as well, funny as it sounds, just use the setter
:
def __init__(self,temperature=0):
self.temperature = temperature
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.