search
HomeBackend DevelopmentPython TutorialDetailed explanation of Python decorator property() tutorial

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
PHP Notice: Trying to get property of non-object - 解决方法PHP Notice: Trying to get property of non-object - 解决方法Aug 17, 2023 am 09:27 AM

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

PHP Notice: Undefined property: 的解决方法PHP Notice: Undefined property: 的解决方法Jun 22, 2023 pm 02:48 PM

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

详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

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

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

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

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

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

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

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

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

MantisBT

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

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

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

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool