首页 > 图灵资讯 > 技术篇>正文

浅析Python装饰器中的@property

2023-04-23 09:45:33

今日鸡汤无法忍受玄鬓影,来对白头吟。

一、使用@property优势

将类法转换为类属性,可用于直接获取属性值或赋值属性。

案例分析

例:

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 = vale = Exam(60)print(e.get_score())e.set_score(70)print(e.get_score())

 

浅析Python装饰器中的@property_html

代码解析:

定义了一个 Exam 类,为了避免直接正确 _score 提供了属性操作 get_score 和 set_score 该方法起到了包装的作用,隐藏了一些不想公开的属性,只为用户提供了一种操作方法。在该方法中,可以检查参数的合理性。

Python 提供了 property 装饰器,装饰方法,可以『当作』属性来用。

例 :

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 = vale = Exam(60)print(e.score)e.score = 90print(e.score)e.score = 200print(e.score)

 

浅析Python装饰器中的@property_css_02

注:

给方法 score 加上了 @property,于是可以把 score 作为属性使用,此时,将创建新的score.setter,它可以将装饰方法转化为属性赋值。

另外,不一定要用。 score.setter 这个装饰器,这个时候 score 它成为一种只读属性:

class Exam(object):    def __init__(self, score):        self._score = score    @property    def score(self):        return self._scoree = Exam(60)print(e.score)e.score = 200  # score 只读属性,值printt不能设置(e.score)

 

浅析Python装饰器中的@property_css_03

二、@property的力量

property是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()。

浅析Python装饰器中的@property_golang_04

2. 属性的作用。

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

例:

c.temperature = 37print(c.temperature)print(c.to_fahrenheit())

 

浅析Python装饰器中的@property_编程语言_05

注:

温度值存储在私有变量_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())

浅析Python装饰器中的@property_css_06

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

语法:

temperature = property(get_temperature,set_temperature)

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

# 创建空属性temperature = property()# 设置 fgettemperature = temperature.getter(get_temperature)# 设置 fsettemperature = 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 = valuec=Celsius()c.temperature = 37print(c.temperature)

 

浅析Python装饰器中的@property_css_07

注:

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

四、总结

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

欢迎积极尝试。有时候看到别人很容易实现,但是当你自己实现的时候,总会有各种各样的问题。不要眼高手低,勤奋动手,这样才能更深刻地理解。

代码很简单,希望对你的学习有帮助。

上一篇 从原理聊JVM(一):染色标记和垃圾回收算法
下一篇 动态规划之机器人走路

文章素材均来源于网络,如有侵权,请联系管理员删除。