Python decorator @property

参考

廖雪峰的官方网站

http://blog.youkuaiyun.com/elevenqiao/article/details/6796770

 

Python version 3.4

1. 定义类Parrot

class Parrot(object): 
    def __init__(self): 
        self._voltage = 100000 
 
    def voltage(self): 
        """Get the current voltage.""" 
        return self._voltage 

>>> s=Parrot()
>>> s.voltage
<bound method Parrot.voltage of <__main__.Parrot object at 0x01C66270>>
>>> s.voltage()
100000

访问voltage函数需要加括号才能得到期望的值100000, 否则返回的是一个函数类型。


2. 加上装饰器property之后,可以像访问属性那样访问函数,不用加括号调用。

class Parrot(object): 
    def __init__(self): 
        self._voltage = 100000 
 
    @property 
    def voltage(self): 
        """Get the current voltage.""" 
        return self._voltage 
 
if __name__ == "__main__": 
    # instance 
    p = Parrot() #实例化类Parrot
    # similarly invoke "getter" via @property 调用p.voltage() 相当于调用@property的getter方法
    print (p.voltage)

调用的时候不用写成p.voltage(),写成p.voltage就可以。


3. 很多时候需要对类中的变量进行修改,需要一个函数做写入。

class Parrot(object): 
    def __init__(self): 
        self._voltage = 100000 
 
    @property 
    def voltage(self): 
        """Get the current voltage.""" 
        return self._voltage
    
    @voltage.setter
    def voltage(self, value): 
        """Set the current voltage.""" 
        self._voltage = value
@voltage.setter 也是一个装饰器,使用了@property的setter方法去装饰voltage函数。

>>> s=Parrot()
>>> s.voltage = 100
>>> s.voltage
100
赋值就调用setter, 没有赋值就调用getter。 可以任性使用s.voltage 。


附: 官方文档中对@property的说明:

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

Return a propertyattribute.

fget is a function for getting an attribute value. fsetis a function for setting an attribute value.fdel is a function fordeleting an attribute value. Anddoc creates a docstring for theattribute.

A typical use is to define a managed attribute x:

class C:

    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

 

    x = property(getx,setx, delx, "I'm the 'x' property.")


If c is an instance of C, c.x will invoke the getter, c.x = value will invokethe setter and del c.x the deleter.

If given, doc will be the docstring of the property attribute. Otherwise, the property will copy fget‘sdocstring (if it exists). This makes it possible to create read-only properties easily using property() as adecorator:

class Parrot:

    def __init__(self):

        self._voltage= 100000

 

    @property

    def voltage(self):

        """Getthe current voltage."""

        return self._voltage


The @property decorator turns the voltage() method into a “getter” for a read-only attribute with the same name, andit sets the docstring forvoltage to “Get the current voltage.”

A property object has getter, setter, and deleter methods usable as decorators that create a copy of theproperty with the correspondingaccessor function set to the decorated function. This is best explained with anexample:

class C:

    def __init__(self):

        self._x = None

 

    @property

    def x(self):

        """I'mthe 'x' property."""

        return self._x

 

    @x.setter

    def x(self, value):

        self._x = value

 

    @x.deleter

    def x(self):

        del self._x


This code is exactly equivalent to the first example. Be sure to give theadditional functions the same name as the originalproperty (x in this case.)

The returned propertyobject also has the attributes fget, fset, and fdel corresponding to the constructor arguments.



这篇文章给出了更详细的说明,值得一读

-->http://www.programiz.com/python-programming/property


装饰器(decorator)是一种可以给函数或类动态添加功能的工具。在Python中,有一些内置的装饰器,比如@staticmethod、@classmethod和@property。 @staticmethod装饰器用于定义静态方法。静态方法是一个和类没有绑定关系的方法,可以直接通过类名调用,也可以通过实例调用。使用@staticmethod装饰器可以将一个方法转变为静态方法。 @classmethod装饰器用于定义类方法。类方法是与类相关联的方法,通过类名调用时,会将类本身作为第一个参数传入。使用@classmethod装饰器可以将一个方法转变为类方法。 @property装饰器用于定义属性。属性是一种特殊的方法,可以像访问属性一样来访问方法。使用@property装饰器可以将一个方法转变为属性。通常,一个@property装饰器会配合一个相应的.setter装饰器使用,来定义属性的设置方法。 举个例子,对于一个名为Student的类: class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value 这个类中的score方法被@property装饰器修饰,使得它可以像属性一样被访问。同时,@score.setter装饰器定义了一个setter方法,用于设置score属性的值。这样,我们可以通过实例的score属性来获取和设置学生的成绩。 总结起来,@staticmethod、@classmethod和@propertyPython内置的装饰器,分别用于定义静态方法、类方法和属性。它们可以让我们的代码更加简洁和易读。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [python面试常问的几个内置装饰器:@staticmethod、@classmethod和@property](https://blog.youkuaiyun.com/weixin_35383324/article/details/113674252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python 使用@property对属性进行数据规范性校验](https://blog.youkuaiyun.com/a772304419/article/details/120813610)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值