Home  >  Article  >  Backend Development  >  Detailed explanation of Python decorator property() tutorial

Detailed explanation of Python decorator property() tutorial

巴扎黑
巴扎黑Original
2017-08-18 13:53:001263browse

1. What is a decorator?

Official definition: Decorator is a very famous design pattern, which is often used in scenarios with cross-cutting requirements. The more classic ones include inserting logs, performance testing, transaction processing, etc. Decorators are an excellent design to solve this kind of problem. With decorators, we can extract the same code in a large number of functions that has nothing to do with the function itself and continue to reuse it. In a nutshell, the purpose of a decorator is to add additional functionality to an existing object.

Python includes a total of three built-in decorators:

① staticmethod

② classmethod

③ property

2. Property function Property() A brief discussion

2.1 Why use property?

Usually, when we access attributes and assign values ​​to attributes, we deal with classes and instances __dict__; but if we want to standardize attribute access, there are two ways available: ① Data descriptor, ②. property() property function.

However, we know that descriptors are relatively complex and difficult to use for novices, so you might as well try property(). Compared to the large process of descriptors, property is equivalent to a thread.

2.2 Function prototype:

property(fget=None, fset=None, fdel=None, doc=None)

2.3 Common method definition:

Suppose there is a private variable __x in calss Normal, as shown in the following code:

#code 1
class Normal:
    def __init__(self):
        self.__x = None
    def getx(self):
        return self.__x
    def setx(self, value):
        self.__x = value
    def delx(self):
        del self.__x
tN = Normal()
print(tN.__count)

Output result (an error is reported)

Traceback (most recent call last):
  File "C:/Users/Administrator/AppData/Local/Programs/Python/Python35/property.py", line 15, in <module>
    print(tN.__count)
AttributeError: &#39;Normal&#39; object has no attribute &#39;__count&#39;

Why is an error reported? Because the attribute __x of instance tN is a private attribute and cannot be accessed directly, we can only call the internally defined method;

tN = Normal()
tN.setx(10)
print(tN.getx())

Output result:

6 10

Using the internal method, you can easily Get the private attribute value of the instance or class;

However, if I want to change the setx method name of class Normal to something else (such as Normal_setx), this function is used in many external places, do I need it? Find the calling location of the method one by one, and then change it one by one?

The C language may be able, but Python, a high-level language, how can it not solve such a problem?

So, how to solve the above problems?

There are actually two methods.

Method 1: Use the property function property()

class Normal:
    def __init__(self):
        self.__x = None
    def getx(self):
        print(&#39;getx(): self.__x=&#39;, self.__x)
        return self.__x
    def setx(self, value):
        self.__x = value
        print(&#39;setx()&#39;)
    def delx(self):
        print(&#39;delx()&#39;)
        del self.__x
    y = property(getx, setx, delx, "I&#39;m a property")
tN=Normal()
tN.y=10
tN.y
del tN.y
#输出结果:
setx()
getx(): self.__x= 10
delx()

Directly operate the method as a property, which is very convenient

Method 2: Use the @property decorator

class Normal:
    
    def __init__(self):
        self.__x = None
    @property
    def xx(self):
        print(&#39;getx(): self.__x=&#39;, self.__x)
        return self.__x
    
    @xx.setter
    def xx(self, value):
        self.__x = value
        print(&#39;setx()&#39;)
    @xx.deleter
    def xx(self):
        print(&#39;delx()&#39;)
        del self.__x
tN=Normal()
tN.xx=10
tN.xx
del tN.xx
#输出结果信息:
setx()
getx(): self.__x= 10
delx()

outputs the same result as method 1, which proves that both methods are feasible (note: the first one must be @property (replacing getter, otherwise an error will be reported)).

The above is the detailed content of Detailed explanation of Python decorator property() tutorial. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn