Table of Contents
1. Advantages of using @property" >1. Advantages of using @property
Case Analysis" >Case Analysis
" >Python provides property decorators. The decorated methods can be used "as" properties.
二、@property的力量" >二、@property的力量
2. 属性的作用。
" >2. 属性的作用。
三、深入了解property" >三、深入了解property
1. 属性对象有三个方法,getter()、setter()和deleter()。" >1. 属性对象有三个方法,getter()、setter()和deleter()。
2. 案例" >2. 案例
四、总结" >四、总结
Home Backend Development Python Tutorial A brief analysis of @property in Python decorators

A brief analysis of @property in Python decorators

Jul 25, 2023 pm 04:18 PM
python Decorator

1. Advantages of using @property

Convert class methods into class attributes, which can be used to directly obtain attribute values ​​or assign values ​​to attributes.

Case Analysis

Example:

class Exam(object):
    def __init__(self, score):
        self._score = score


    def get_score(self):
        return self._score


    def set_score(self, val):
        if val < 0:
            self._score = 0
        elif val > 100:
            self._score = 100
        else:
            self._score = val


e = Exam(60)
print(e.get_score())


e.set_score(70)
print(e.get_score())
Copy after login

A brief analysis of @property in Python decorators

##Code analysis:

# defines an Exam class. In order to avoid direct operations on the _score attribute, the get_score and set_score methods are provided, so It plays the role of encapsulation, hiding some attributes that do not want to be exposed to the outside world, and only provides methods for users to operate. In the methods, the rationality of parameters can be checked, etc.

Python provides property decorators. The decorated methods can be used "as" properties.

Example:

class Exam(object):
    def __init__(self, score):
        self._score = score


    @property
    def score(self):
        return self._score


    @score.setter
    def score(self, val):
        if val < 0:
            self._score = 0
        elif val > 100:
            self._score = 100
        else:
            self._score = val




e = Exam(60)
print(e.score)


e.score = 90
print(e.score)


e.score = 200
print(e.score)
Copy after login

A brief analysis of @property in Python decorators

##Note:

Add @property to the method score, so score can be used as a property. At this time, a new score.setter will be created, which can set the decorated method Become an attribute to assign a value to.

In addition, you do not have to use the score.setter decorator, then score becomes a read-only property:

class Exam(object):
    def __init__(self, score):
        self._score = score


    @property
    def score(self):
        return self._score


e = Exam(60)
print(e.score)
e.score = 200  # score 是只读属性,不能设置值
print(e.score)
Copy after login

A brief analysis of @property in Python decorators


二、@property的力量

python处理上述问题的方法是使用property。可以这样来实现它。

例 :

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature


    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


    def get_temperature(self):
        print("获得的值")
        return self._temperature


    def set_temperature(self, value):
        if value < -273:
            raise ValueError("零下273度是不可能的")
        print("设定值")
        self._temperature = value


    temperature = property(get_temperature,set_temperature)
Copy after login

并且,一旦运行,在shell中发出以下代码。

c = Celsius()
print(c.temperature)
Copy after login

创建对象时,将调用init ()方法。此方法的线为self.temperature = temperature。

此分配自动称为set_temperature()。

A brief analysis of @property in Python decorators

2. 属性的作用。

任何访问如c.temperature都会自动调用get_temperature()。

例:

c.temperature = 37
print(c.temperature)
print(c.to_fahrenheit())
Copy after login

A brief analysis of @property in Python decorators

注:

温度值存储在私有变量_temperature中。temperature属性是一个属性对象,它提供了与此私有变量的接口。


三、深入了解property

在Python中,property()是一个内置函数,用于创建并返回属性对象。

语法

property(fget=None, fset=None, fdel=None, doc=None)
Copy after login

参数解析

fget为获取属性值的函数,fset为设置属性值的函数,fdel为删除属性的函数,doc为字符串(如注释)。从实现中可以看出,这些函数参数是可选的。

可以简单地按照以下方式创建属性对象。

property(fget=None, fset=None, fdel=None, doc=None)
print(property())
Copy after login

A brief analysis of @property in Python decorators

1. 属性对象有三个方法,getter()、setter()和deleter()。

语法:

temperature = property(get_temperature,set_temperature)
Copy after login

用于稍后指定fget、fset和fdel。

# 创建空属性
temperature = property()
# 设置 fget
temperature = temperature.getter(get_temperature)
# 设置 fset
temperature = temperature.setter(set_temperature)
Copy after login

注:

这两段代码是等效的。

不定义名称get_temperature,set_temperature。

因为它们是不必要的,并且会影响类命名空间。为此,在定义getter和setter函数时重用了名称temperature。

2. 案例

例:

class Celsius:
    def __init__(self, temperature = 0):
        self._temperature = temperature


    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


    @property
    def temperature(self):
        print("获得值")
        return self._temperature


    @temperature.setter
    def temperature(self, value):
        if value < -273:
            raise ValueError("零下273度是不可能的")
        print("零下273度是不可能的")
        self._temperature = value
c=Celsius()
c.temperature = 37
print(c.temperature)
Copy after login

A brief analysis of @property in Python decorators

注:

实现是制作属性的简单方法和推荐方法。在Python中寻找属性时,很可能会遇到这些类型的构造。


四、总结

本文基于Python基础,介绍了@property 如何把方法变成了属性。通过案例的分析,代码的展示。介绍了@property的力量,以及提供了相应错误的解决方案处理方法。属性的作用。

The above is the detailed content of A brief analysis of @property in Python decorators. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles