python 中的@property的用法详解

目录
  • 1.什么是property
  • 2.property属性定义的两种方式
  • 3.用property代替getter和setter方法

1.什么是property

简单地说就是一个类里面的方法一旦被@property装饰,就可以像调用属性一样地去调用这个方法,它能够简化调用者获取数据的流程,而且不用担心将属性暴露出来,有人对其进行赋值操作(避免使用者的不合理操作)。需要注意的两点是

  • 调用被装饰方法的时候是不用加括号的
  • 方法定义的时候有且只能有self一个参数
>>> class Goods():
        def __init__(self,unit_price,weight):
            self.unit_price = unit_price
            self.weight = weight
        @property
        def price(self):
            return self.unit_price * self.weight
>>> lemons = Goods(7,4)
>>>
>>> lemons.price
28

上面通过调用属性的方式直接调用到 price 方法,property把复杂的处理过程封装到了方法里面去,取值的时候调用相应的方法名即可。

2.property属性定义的两种方式

A、装饰器方式

在类的方法上应用@property装饰器,即上面那种方式。

B、类属性方式

创建一个实例对象赋值给类属性

>>> class Lemons():
        def __init__(self,unit_price=7):
            self.unit_price = unit_price
        def get_unit_price(self):
            return self.unit_price
        def set_unit_price(self,new_unit_price):
            self.unit_price = new_unit_price
        def del_unit_price(self):
            del self.unit_price
        x = property(get_unit_price, set_unit_price, del_unit_price)
>>> fruit = Lemons()
>>>
>>> fruit.x                         #调用 fruit.x 触发 get_unit_price
7
>>>
>>> fruit.x = 9                     #调用 fruit.x = 9 触发 set_unit_price
>>>
>>> fruit.x
9
>>>
>>> fruit.unit_price                #调用 fruit.unit_price 触发 get_unit_price
9
>>> del fruit.x                     #调用 del fruit.x 触发 del_unit_price
>>>
>>> fruit.unit_price
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    l.unit_price
AttributeError: 'Lemons' object has no attribute 'unit_price'

property方法可以接收四个参数

  • 第一个参数是获得属性的方法名,调用 对象.属性时自动触发
  • 第二个参数是设置属性的方法名, 给属性赋值时自动触发
  • 第三个参数是删除属性的方法名,删除属性时自动触发
  • 第四个参数是字符串,是属性的描述文档,调用对象.属性.doc时触发

3.用property代替getter和setter方法

>>>class Watermelon():
       def __init__(self,price):
           self._price = price                  #私有属性,外部无法修改和访问

       def get_price(self):
           return self._price

       def set_price(self,new_price):
           if new_price > 0:
               self._price = new_price
           else:
               raise 'error:价格必须大于零'

用property代替getter和setter

>>>class Watermelon():
       def __init__(self,price):
           self._price = price
       @property                          #使用@property装饰price方法
       def price(self):
           return self._price
       @price.setter                      #使用@property装饰方法,当对price赋值时,调用装饰方法
       def price(self,new_price):
           if new_price > 0:
               self._price = new_price
           else:
               raise 'error:价格必须大于零'
>>> watermelon = Watermelon(4)
>>>
>>> watermelon.price
4
>>>
>>> watermelon.price = 7
>>>
>>> watermelon.price
7

到此这篇关于python @property的用法的文章就介绍到这了,更多相关python @property的用法内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python @property原理解析和用法实例

    这篇文章主要介绍了Python @property原理解析和用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在我们定义数据库字段类的时候,往往需要对其中的类属性做一些限制,一般用get和set方法来写,那在python中,我们该怎么做能够少写代码,又能优雅的实现想要的限制,减少错误的发生呢,这时候就需要我们的@property闪亮登场啦,巴拉巴拉能量--.. 用代码来举例子更容易理解,比如一个学生成绩表定义成这样 class Stude

  • python @property的用法及含义全面解析

    在接触python时最开始接触的代码,取长方形的长和宽,定义一个长方形类,然后设置长方形的长宽属性,通过实例化的方式调用长和宽,像如下代码一样. class Rectangle(object): def __init__(self): self.width =10 self.height=20 r=Rectangle() print(r.width,r.height) 此时输出结果为10 20 但是这样在实际使用中会产生一个严重的问题,__init__ 中定义的属性是可变的,换句话说,是使用一个

  • 介绍Python的@property装饰器的用法

    在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: s = Student() s.score = 9999 这显然不合逻辑.为了限制score的范围,可以通过一个set_score()方法来设置成绩,再通过一个get_score()来获取成绩,这样,在set_score()方法里,就可以检查参数: class Student(object): def get_score(self): return self._score def set_s

  • 实例讲解Python编程中@property装饰器的用法

    取值和赋值 class Actress(): def __init__(self): self.name = 'TianXin' self.age = 5 类Actress中有两个成员变量name和age.在外部对类的成员变量的操作,主要包括取值和赋值.简单的取值操作是x=object.var,简单的赋值操作是object.var=value. >>> actress = Actress() >>> actress.name #取值操作 'TianXin' >&g

  • Python 中@property的用法详解

    在绑定属性时,如果我们直接把属性赋值给对象,比如: p = Person() p.name= 'Mary' 我们先看个详细的例子(注意双下划线name和age定义为私有变量): class Person(object): def __init__(self, name, age): self.__name = name self.__age = age def get_age_fun(self): return self.__age def set_age_fun(self, value): i

  • Python 类,property属性(简化属性的操作),@property,property()用法示例

    本文实例讲述了Python 类,property属性(简化属性的操作),@property,property()用法.分享给大家供大家参考,具体如下: property属性的创建方式有两种:1.@property装饰器方式   2.类属性方式 ( 类属性=property() ) property属性可以简化实例对象对属性的操作(获取.设置),可以对属性做类型校验和预处理等. 装饰器方式: demo.py(@property,获取属性值,旧式类与新式类都有的方式): class Goods: @

  • python 中的@property的用法详解

    目录 1.什么是property 2.property属性定义的两种方式 3.用property代替getter和setter方法 1.什么是property 简单地说就是一个类里面的方法一旦被@property装饰,就可以像调用属性一样地去调用这个方法,它能够简化调用者获取数据的流程,而且不用担心将属性暴露出来,有人对其进行赋值操作(避免使用者的不合理操作).需要注意的两点是 调用被装饰方法的时候是不用加括号的 方法定义的时候有且只能有self一个参数 >>> class Goods(

  • python中for in的用法详解

    for in 说明:也是循环结构的一种,经常用于遍历字符串.列表,元组,字典等 格式: for x in y:     循环体 执行流程:x依次表示y中的一个元素,遍历完所有元素循环结束. 例1:遍历字符串 s = 'I love you more than i can say' for i in s: print(i) 例2:遍历列表 l = ['鹅鹅鹅', '曲项向天歌', '锄禾日当午', '春种一粒粟'] for i in l: print(i) # 可以获取下表,enumerate每次

  • Python中的装饰器用法详解

    本文实例讲述了Python中的装饰器用法.分享给大家供大家参考.具体分析如下: 这里还是先由stackoverflow上面的一个问题引起吧,如果使用如下的代码: 复制代码 代码如下: @makebold @makeitalic def say():    return "Hello" 打印出如下的输出: <b><i>Hello<i></b> 你会怎么做?最后给出的答案是: 复制代码 代码如下: def makebold(fn):    

  • python中的lambda表达式用法详解

    本文实例讲述了python中的lambda表达式用法.分享给大家供大家参考,具体如下: 这里来为大家介绍一下lambda函数. lambda 函数是一种快速定义单行的最小函数,是从 Lisp 借用来的,可以用在任何需要函数的地方 .下面的例子比较了传统的函数定义def与lambda定义方式: >>> def f ( x ,y): ... return x * y ... >>> f ( 2,3 ) 6 >>> g = lambda x ,y: x *

  • Python中 map()函数的用法详解

    map( )函数在算法题目里面经常出现,map( )会根据提供的函数对指定序列做映射,在写返回值等需要转换的时候比较常用. 关于映射map,可以把[ ]转成字符串的话,就不需要用循环打印字符串输出结果这种比较旧的方式. 在Python 3中的例子如下: 也可以用匿名函数来计算幂计算: map(lambda x:x**2,[1,2,3,4,5]) 也可以用来规范输出: name_list={'tony','cHarLIE','rachAEl'} def format_name(s): ss=s[0

  • python中metaclass原理与用法详解

    本文实例讲述了python中metaclass原理与用法.分享给大家供大家参考,具体如下: 什么是 metaclass. metaclass (元类)就是用来创建类的类.在前面一篇文章<python动态创建类>里我们提到过,可以用如下的一个观点来理解什么是metaclass: MyClass = MetaClass() MyObject = MyClass() metaclass是python 里面的编程魔法 同时在前面一篇<python动态创建类>文章里描述动态创建class 的

  • Python中return self的用法详解

    在Python中,有些开源项目中的方法返回结果为self. 对于不熟悉这种用法的读者来说,这无疑使人困扰,本文的目的就是给出这种语法的一个解释,并且给出几个例子. 在Python中,return self的作用为:(英语原文,笔者水平有限,暂不翻译) Returning self from a method simply means that your method returns a reference to the instance object on which it was called

  • Python中selenium库的用法详解

    selenium主要是用来做自动化测试,支持多种浏览器,爬虫中主要用来解决JavaScript渲染问题. 模拟浏览器进行网页加载,当requests,urllib无法正常获取网页内容的时候 一.声明浏览器对象 注意点一,Python文件名或者包名不要命名为selenium,会导致无法导入 from selenium import webdriver #webdriver可以认为是浏览器的驱动器,要驱动浏览器必须用到webdriver,支持多种浏览器,这里以Chrome为例 browser = w

  • python中list.copy方法用法详解

    当我们想复制两个一模一样的列表时,我们可能使用到list.copy()这个方法,这个方法可以让我们复制一个相同的数组,当遇到下面这种情况时,可能会遇到一些问题 # _*_coding='utf8'_*_ nameList = [1, 2, 3, 4, 5] nameList1 = nameList.copy() nameList[1] = 55 print(nameList, nameList1) 此时打印出nameList和nameList1时,两个列表的元素是下面这样 [1, 55, 3,

  • Python中装饰器高级用法详解

    在Python中,装饰器一般用来修饰函数,实现公共功能,达到代码复用的目的.在函数定义前加上@xxxx,然后函数就注入了某些行为,很神奇!然而,这只是语法糖而已. 场景 假设,有一些工作函数,用来对数据做不同的处理: def work_bar(data): pass def work_foo(data): pass 我们想在函数调用前/后输出日志,怎么办? 傻瓜解法 logging.info('begin call work_bar') work_bar(1) logging.info('cal

随机推荐