search
HomeBackend DevelopmentPython TutorialA brief analysis of @property in Python decorators

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())

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)

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)

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)

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

c = Celsius()
print(c.temperature)

创建对象时,将调用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())

A brief analysis of @property in Python decorators

注:

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


三、深入了解property

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

语法

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

参数解析

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

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

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

A brief analysis of @property in Python decorators

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

语法:

temperature = property(get_temperature,set_temperature)

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

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

注:

这两段代码是等效的。

不定义名称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)

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
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

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

Video Face Swap

Video Face Swap

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

Hot Tools

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 Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools