In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to use the @ property decorator in python. It is very detailed and has a certain reference value. Friends who are interested must finish it!
I. the use of property decorator
Let's start with a simple explanation of the little chestnut:
Class property (fget=None,fset=None,fdel=None,doc=None)
Fget is a function used to get the value of an attribute
Fset is a function used to set property values
Fdel is a function used to delete attribute values
Doc creates a document string for the property object
Using property, you can change the method of a class into an attribute of the same name, which is more concise to use. Finally, an example shows
It is recommended to use property decorator directly, which is relatively concise. The following is an official example. Use @ property decoration method x to turn it into an attribute with the same name. Through fget, fset, and fdel, you can control the read-write deletion attribute of x.
Class C: def _ _ init__ (self): self._x = None @ property def x (self): "I am the 'x' property." Return self._x # set fset, note that x should be the same as @ property modified method name @ x.setter # this fset name is not limited, it is recommended to be the same as x def x (self, value): self._x = value # set fdel @ x.deleter def x (self): del self._x
Needless to say, to go straight to the example, set a readable and writable birthYear property, a readable gender property, a readable and writeable weight attribute, and an age attribute inferred by birthYear in the class Man
"" @ property, @ * .setter "" from datetime import datetimeclass Man: def _ _ init__ (self, birthYear=None, gender=None, weight=None): "" 1. Use @ property to hide private attributes, such as hiding the'_ birthYear' attribute and taking the property object birthYear as the external attribute "self._birthYear = birthYear self._gender = gender self._weight = weight @ property def birthYear (self): return self._birthYear @ birthYear.setter def birthYear (self, value):"2. You can restrict attribute input or other operations in setter "" assert not value > datetime.now () .year, f'please input the right valuevalues' Self._birthYear = value @ property "3. Get the age directly by using obj.age Instead of writing the method obj.age (), it is more natural and convenient. "" def age (self): return datetime.now (). Year-self._birthYear @ property def gender (self): return self._gender @ property def weight (self): return self._weight @ weight.setter def weight (self) Value): self._weight = value @ weight.deleter def weight (self): del self._weightlilei = Man (1996, 'male', 180) age = lilei.ageprint (' Lilei is {} years old\ n'.format (age)) # set gender try: lilei.gender = 'female'except: print (' gender cannot be changed! \ n') # Update weight print (weight before f'lilei weight: {lilei.weight}\ n') lilei.weight = 200print (weight after f'lilei weight loss: {lilei.weight}\ n') print ('lilei deleted weight information after a weight loss failure') del lilei.weighttry: print ('weight of lilei {}' .format (lilei.weight)) except: print ('weight information of lilei not found!')
Output result:
Lilei is 25 years old.
Gender cannot be changed!
Lilei weight before weight loss: 180
Lilei's weight after weight loss: 200
Lilei deleted the weight information after losing weight after failing to lose weight.
Can't find lilei's weight information!
Second, give some examples
Now let's take a closer look at why the python built-in property modifier exists and what problems can be solved?
To start with a concrete example, define a class that represents degrees Celsius and this class contains a method for converting from degrees Celsius to Fahrenheit.
1. Implementation without setter and getter methods # initial version class Celsius: def _ init__ (self, temperature = 0): self.temperature = temperature def to_fahrenheit (self): return (self.temperature * 1.8) + 3 degrees instantiate human = Celsius () # set temperature human.temperature = 3 degrees get temperature print (human.temperature) # call the built-in method to convert degrees Celsius to print (human.to_fahrenheit ())
Output result:
thirty-seven
98.60000000000001
two。 Use the implementation of setter and getter to increase the limit of temperature input
But if someone asks human.temperature to be-273.15 now, we know that it is impossible for the temperature to be lower than-300. at this time, we need to limit the temperature value. the conventional method is to set a temperature value of setter and getter, and the temperature value is stored in _ temperature.
# Update temperature limit version class Celsius: def _ init__ (self, temperature=0): self.set_temperature (temperature) def to_fahrenheit (self): return (self.get_temperature () * 1.8) + 32 # getter method def get_temperature (self): return self._temperature # setter method def set_temperature (self, value): if value
< -273.15: raise ValueError("摄氏温度不可能低于 -273.15 !") self._temperature = value# 实例化human = Celsius(37)# 使用添加的getter获取温度值print(human.get_temperature())# 调用内置方法将摄氏度转化为华氏温度print(human.to_fahrenheit())# 使用添加的setter对温度值进行设置human.set_temperature(-300)# Get the to_fahreheit methodprint(human.to_fahrenheit()) 毫无疑问,在设置温度值等于-300的时候肯定会报错,但是这个时候你可能发现设置和获取温度值的代码发生变化而且更复杂 并且 你需要对Celsius类的初始化函数进行更改,self.temperature = temperature到 self.set_temperature(temperature), 如果现在是一个拥有很多属性的类, 一个一个去进行这样的更改是很麻烦的,而且可能会导致与这个类别相关的代码出现错误, 有没有更好的实现方式呢?这个时候就该今天的主角property装饰器出场了 3.利用property装饰器实现的版本# 使用 @property 装饰器版本class Celsius: def __init__(self, temperature=0): #这里的self.temperture是下面定义的property对线 temperatue #所以你会发现在初始化Celsius时, 调用了temperature.setting方法 self.temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 @property def temperature(self): print("获取温度值...") return self._temperature @temperature.setter def temperature(self, value): print("设置温度值...") if value < -273.15: raise ValueError("摄氏温度不可能低于 -273.15 !") self._temperature = value# 用property的实现后获取和设置温度值与最初的版本一样!human = Celsius()# 设置温度human.temperature = 37# 获取温度值print(human.temperature)# 调用内置方法将摄氏度转化为华氏温度print(human.to_fahrenheit())#测试温度限制功能human.temperature = -300 输出结果: 设置温度值... 设置温度值... 获取温度值... 37 获取温度值... 98.60000000000001 设置温度值... --------------------------------------------------------------------------- ValueError Traceback (most recent call last) d:\2.github\python_demo\016_decorator.py in 30 31 #测试温度限制功能 --->32 human.temperature =-300
D:\ 2.github\ python_demo\ 016_decorator.py in temperature (self, value)
16 print ("set temperature value.")
17 if value
< -273.15: --->18 raise ValueError ("the temperature cannot be lower than-273.15!")
19 self._temperature = value
twenty
ValueError: the temperature cannot be lower than-273.15 degrees Celsius!
You can see that the temperature setting is limited and the code that gets and sets the temperature value is exactly the same as the original version, that is, the code is backward compatible
The above is all the content of the article "how to use the @ property decorator in python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.