Property is a recommended way to set and get member variables, especially private ones. The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.
The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.
Here are two different ways to use the property, which have the same effect. The first one is encouraged cause it is more clear, and don't forget to create the class as the descendent of "object"
-
class Celsius(object):
-
def __init__(self, temperature = 0):
-
self._temperature = temperature
-
-
def to_fahrenheit(self):
-
return (self.temperature * 1.8) + 32
-
-
@property
-
def temperature(self):
-
print("Getting value")
-
return self._temperature
-
-
@temperature.setter
-
def temperature(self, value):
-
if value < -273:
-
raise ValueError("Temperature below -273 is not possible")
-
print("Setting value")
-
self._temperature = value
-
-
-
print("this firts line\n")
-
c = Celsius(5)
-
c.temperature = 10
-
deg = c.temperature
-
print("temperature is %s\n" %deg)
Second one:
-
class Celsius(object):
-
def __init__(self, temperature = 0):
-
print("init\n")
-
self.temperature = temperature
-
-
def to_fahrenheit(self):
-
return (self.temperature * 1.8) + 32
-
-
def get_temperature(self):
-
print("Getting value")
-
return self._temperature
-
-
def set_temperature(self, value):
-
if value < -273:
-
raise ValueError("Temperature below -273 is not possible")
-
print("Setting value")
-
self._temperature = value
-
-
temperature = property(get_temperature,set_temperature)
-
-
print("this firts line\n")
-
c = Celsius(5)
-
deg = c.temperature
-
print("temperature is %s\n" %deg)
-
-
d = Celsius(10)
-
deg = d.temperature
-
print("temperature is %s\n" %deg)
阅读(1325) | 评论(0) | 转发(0) |