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: 'Normal' object has no attribute '__count'
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('getx(): self.__x=', self.__x) return self.__x def setx(self, value): self.__x = value print('setx()') def delx(self): print('delx()') del self.__x y = property(getx, setx, delx, "I'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('getx(): self.__x=', self.__x) return self.__x @xx.setter def xx(self, value): self.__x = value print('setx()') @xx.deleter def xx(self): print('delx()') 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!

PHPNotice:Tryingtogetpropertyofnon-object-解决方法在PHP开发过程中,我们可能会遇到一个常见的错误提示:Tryingtogetpropertyofnon-object(试图获取非对象的属性)。这个错误通常是由我们对一个非对象类型的变量尝试访问属性(或调用方法)时引起的。这篇文章将向你介绍这

在使用PHP编写代码时,我们可能会遇到“Notice:Undefinedproperty”这个错误提示。这个错误提示意味着我们正在访问一个未定义的属性,通常是因为该属性在代码中尚未被初始化。那么,该如何解决这个问题呢?下面是几种可能的解决方法:初始化属性这是解决该问题的最简单方法。在代码中显式地初始化属性,可以确保它在使用前已经被定义。例如:class

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool