I have the following Python-Code. I just can't get the instance variable to be read only. Help appreciated.
class Parrot(object):
def __init__(self):
self._voltage = '100000'
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
a = Parrot()
print(a._voltage)
a._voltage = '500000'
print(a._voltage)
Edit:
The point of this question was to understand, how a property could replace the old variable. Somehow everybody just points out that Python is about being mature, and that it is our responsibility not to use "private" variables, since they are visible in python. But nobody pointed out that you'd just turn the old variable in this case
voltage
private
_voltage
and replace the old variable (voltage) with the property
@property
def voltage(self):
which would leave the way you access attributes in this class the same, so that nobody who uses this class has to change their code.
-- like the way you access variables, since you can still access the property like a variable -- e.g.:
a.voltage = 'over 9000'
But it gives more control to the developers of this class (turn voltage to read only). I just felt that nobody did actually explain the mechanics of properties in an understandable way... -> I was not able to understand properties although I googled first. Anyways... kinda ridiculous, since it does not seem to pose any kind of difficulties now.
Cheers
Nimi