In this post I will discuss the common usage of function decorators, specifically the class property decorator as well as the difference between using the decorator or the class method directly.
Looks familiar, doesn't it?
The ubiquitous @propery decorator is found everywhere, but how does it actually work?
What are the differences between using @property or using the property() class method directly?
Here's an example of a standard decorator function.
Under the Python hood, the function that calls the decorator (ie. the outer function) gets wrapped with additional code by calling the decorator and passing the outer function as a parameter. The decorator will create a wrapped function with all it's new logic and return it as the value of the outer function.
The class property method is a built-in Python function that that allows us to define getter, setter and deleter methods for class attributes, and binds them to the class default magic methods.
def get_my_value(self): return self._my_value my_value = property(get_my_value)
is understood by the Python compiler as
def __get__(self,obj): return self.fget(obj)
Essentially, the property() method creates an object that acts as a proxy between the attribute name and the underlying data. It therefore allows us to add custom behavior and validation logic that wouldn't be possible with the default magic methods.
As we see above, the property method allows us to overwrite the default magic method and extent its functionality. We've also demonstrated how a decorator wraps functional logic within a new function. When a getter, setter or deleter method is called with the @property decorator, Python translates it into a call to the property() method internally, and creates a property object that wraps the method to a function that can overwrite the default magic methods.
While we have demonstrated that using the @property decorator or property() method are equivalent, the decorator offers a simpler use, and allows the code within the class to be more readable. It is therefore considered best practice and coding convention and the decorator should be used unless there is a specific scenario requirement.
https://www.geeksforgeeks.org/python-property-decorator-property/
Blog post header image generator
Code snippet maker
The above is the detailed content of Decorators & Class Property in Python. For more information, please follow other related articles on the PHP Chinese website!