First knew decorator and @property
Welcome. In this article, we will learn in detail how to use the Python decorator and @property.
You will learn the content:
- The advantage of using the decorator.
- The advantages of using @property.
- Basics decorator functions: What they are and how to associate it with @property.
- How to use @property define getter, setter, and deleter.
In Python decorator advantage
- In uncertain call other code block to the existing function, without changing the existing functions to ensure the code is stable and reliable, to avoid potential problems modify existing functions arising.
- Expand the original function function.
Python @property advantage in
property can be viewed using the attribute "Pythonic" way, because:
- The syntax for defining property of concise and easy to read.
- You can fully access the instance property, just like public property.
- By using @property, you can re-use the name of the property, in order to avoid creating a new name for the getter, setter, and deleter.
Decorative Introduction
Decorator function (decorator function) is a function, it can add new functionality to existing functions (the "existing function" as an argument). Decorator function like giving ice cream (on behalf of that another function) to add a small amount of chocolate (on behalf of that new feature). I.e., add new functionality to an existing function, and does not make any modifications to update an existing function.
. 1 DEF Decorator (FUNC): 2 Print ( " in the interior function, a modification: " , FUNC. The __name__ ) . 3 DEF new_function (): . 4 Print ( " New, then the function is performed: " , FUNC. The __name__ ) . 5 FUNC () . 6 return new_function . 7 . 8 @decorator . 9 DEF initial_function (): 10 Print ( " existing function function " ) . 11 12 is initial_function ()
The output is:
In the interior decorator function, modified: initial_function
new features, and then perform the function of: initial_function
existing functions function
Code when not in use decorator function, to achieve the above functions as follows:
. 1 DEF Decorator (FUNC): 2 Print ( " in the interior function, a modification: " , FUNC. The __name__ ) . 3 DEF new_function (): . 4 Print ( " New, then the function is performed: " , FUNC. The __name__ ) . 5 FUNC () . 6 return new_function . 7 . 8 . 9 DEF initial_function (): 10 Print ( " existing function function " ) . 11 12 is initial_function = Decorator (initial_function) 13 initial_function()
This two pieces of code to achieve the same function. Decoration is an alternative to the above code initial_function = decorator (initial_function) syntactic sugar, an increase of only one line of code can be packaged into an existing function decorator function.
Comparison of the two implementations, the decorator can be understood as the replacement @decorator initial_function = decorator (initial_function) to achieve this statement.
Decorator more concise, there are two parts: first, the definition used for packaging or "decorative" decorator function other functions; then immediately was previously defined wrapper function, add "@" and decorator function name. Here decorator function should be a function parameter, the return value is a function.
The practical application of @property
House defines a class (class instance attributes defined only price). Creating a house instance of the class by House
1 class House: 2 def __init__(self, price): 3 self.price = price 4 5 house = House()
This example is public property price, so the point can be used to directly access and modify property values notation.
1 # Access value 2 house.price 3 4 # Modify value 5 house.price = 40000
However, in general we do not want users to directly access and modify the attribute value, the instance of private property, and the use of getter and setter methods indirect access and modify private instance attribute, the code is updated as follows:
class House: def __init__(self, price): self.__price = price def get_price(self): return self.__price def set_price(self, new_price): self.__price = new_price
Before accessing the tag modifications require the instance attribute, the corresponding client code needs to be modified:
1 # Changed from house.price 2 house.get_price() 3 4 # Changed from house.price = 40000 5 house.set_price(40000)
In response to the above situation, @ property came into being to solve the problem when the direct use code refactoring instance attributes.
1 class House: 2 def __init__(self, price): 3 self.__price = price 4 5 @property 6 def price(self): 7 return self.__price 8 9 @price.setter 10 def price(self, new_price): 11 if new_price > 0 and isinstance(new_price, float): 12 self.__price = new_price 13 else: 14 print("Please enter a valid price") 15 16 @price.deleter 17 def price(self): 18 del self.__price
At this point, you can access the same instance properties as before. Examples of attributes may be employed conventional i.e. initial development, the future may be switched according to the properties required wherever seamless, client code is no need to change.
getter
1 house = House(50000.0) # Create instance 2 print(house.price) # Access value
The output is:
50000.0
setter
1 house = House(50000.0) # Create instance 2 house.price = 88888.0 # Update value 3 print(house.price)
The output is:
88888.0
deleter
1 # Delete the instance attribute 2 del house.price 3 4 # The instance sttribute doesn't exist 5 print(house.price)
The output is:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-13-dd54e9ad0090> in <module> 1 # The instance sttribute doesn't exist ----> 2 print(house.price) <ipython-input-8-5e2f43c64399> in price(self) 5 @property 6 def price(self): ----> 7 return self.__price 8 9 @price.setter AttributeError: 'House' object has no attribute '_House__price'
to sum up
- Use @property decorator and Python code may be such concise and easy to read.
- @property can be regarded as defined getter, setter and deleter of "pythonic" way.
- Modify the class internal implementation without affecting the program, so as to avoid direct access and modification of data.
references
- https://www.freecodecamp.org/news/python-property-decorator/
- "Python Quick Start" (third edition)