@property defined as int
The following code is taken from Python Docs:
class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
When I run:
parrot = Parrot()
print(parrot.voltage)
parrot.voltage = 100
print(parrot.voltage)
I get the following output (as expected, as no setter is defined)
{0: 100000}
Traceback (most recent call last):
File "prop.py", line 13, in <module>
parrot.voltage = 100
AttributeError: can't set attribute
@property defined as dict
However, if I define self._voltage = {}
the property becomes writeable:
class Parrot(object):
def __init__(self):
self._voltage = {}
self._voltage[0] = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
parrot = Parrot()
print(parrot.voltage)
parrot.voltage[0] = 100
print(parrot.voltage)
The output is then:
{0: 100000}
{0: 100}
Same behavior in Python 2.7.9 and Python 3.4.3. Why is the property writeable, even if no setter is explicitly defined in the code? Here it was proposed to subclass dict
to get this behavior. However, it seems that this not required.