[英]No output from property setter when appending instance to list
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).在下面的示例中,我从直接初始化的 class 实例( fiver
部分)获得了预期的 output,但在将实例附加到列表( objlist
部分)时却没有。 Python 3.5.3 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.在您的__init__
中,您直接设置“内部”值_temperature
。 This doesn't call the setter
, as the property.setter
is defined over temperature
.这不会调用setter
,因为property.setter
是在temperature
上定义的。
If you want the __init__
to pass through the setter
validation as well, funny as it sounds, just use the setter
:如果您希望__init__
也通过setter
验证,听起来很有趣,只需使用setter
:
def __init__(self,temperature=0):
self.temperature = temperature
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.