@property 可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/getter也是需要的,我们视具体情况吧

请注意以下代码场景:

代码片段1:

Python2.6代码  
  1. class Parrot(object):
  2. def __init__(self):
  3. self._voltage = 100000
  4. @property
  5. def voltage(self):
  6. """Get the current voltage."""
  7. return self._voltage
  8. if __name__ == "__main__":
  9. # instance
  10. p = Parrot()
  11. # similarly invoke "getter" via @property
  12. print p.voltage
  13. # update, similarly invoke "setter"
  14. p.voltage = 12

代码片段2:

Python2.6代码  
  1. class Parrot:
  2. def __init__(self):
  3. self._voltage = 100000
  4. @property
  5. def voltage(self):
  6. """Get the current voltage."""
  7. return self._voltage
  8. if __name__ == "__main__":
  9. # instance
  10. p = Parrot()
  11. # similarly invoke "getter" via @property
  12. print p.voltage
  13. # update, similarly invoke "setter"
  14. p.voltage = 12

代码1、2的区别在于 
class Parrot( object):

在python2.6下,分别运行测试 
片段1:将会提示一个预期的错误信息 AttributeError: can't set attribute 
片段2:正确运行

参考python2.6文档,@property将提供一个ready-only property,以上代码没有提供对应的@voltage.setter,按理说片段2代码将提示运行错误,在python2.6文档中,我们可以找到以下信息:

BIF: 
property([fget[, fset[, fdel[, doc]]]]) 
Return a property attribute for new-style classes (classes that derive from object). 
原来在python2.6下,内置类型 object 并不是默认的基类,如果在定义类时,没有明确说明的话(代码片段2),我们定义的Parrot(代码片段2)将不会继承object

而object类正好提供了我们需要的@property功能,在文档中我们可以查到如下信息:

new-style class 
Any class which inherits from object. This includes all built-in types like list and dict. Only new-style classes can use Python's newer, versatile features like __slots__,  descriptors,  properties, and __getattribute__().

同时我们也可以通过以下方法来验证

Python 2.6代码  
  1. class A:
  2. pass

>>type(A) 
<type 'classobj'>

Python 2.6代码  
  1. class A(object):
  2. pass

>>type(A) 
<type 'type'>

从返回的<type 'classobj'>,<type 'type'>可以看出<type 'type'>是我们需要的object类型(python 3.0 将object类作为默认基类,所以都将返回<type 'type'>)

为了考虑代码的python 版本过渡期的兼容性问题,我觉得应该定义class文件的时候,都应该显式定义object,做为一个好习惯

最后的代码将如下:

Python代码  
  1. class Parrot(object):
  2. def __init__(self):
  3. self._voltage = 100000
  4. @property
  5. def voltage(self):
  6. """Get the current voltage."""
  7. return self._voltage
  8. @voltage.setter
  9. def voltage(self, new_value):
  10. self._voltage = new_value
  11. if __name__ == "__main__":
  12. # instance
  13. p = Parrot()
  14. # similarly invoke "getter" via @property
  15. print p.voltage
  16. # update, similarly invoke "setter"
  17. p.voltage = 12

另外,@property是在2.6、3.0新增的,2.5没有该功能。

python @property相关推荐

  1. python property内建函数的介绍

    为什么80%的码农都做不了架构师?>>>    函数property的基本功能就是把类中的方法当作属性来访问,下面以一个有意思的例子介绍一下: 假如有一只猫,它忘了它喜欢吃什么,下面 ...

  2. python @property

    在绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改: s = Student() s.score = 9999 这显然不合逻辑.为了限制score的 ...

  3. python property理解

    一般情况下我这样使用property: @property def foo(self):return self._foo# 下面的两个decrator由@property创建 @foo.setter ...

  4. python property作用_python中@property的作用和getter setter的解释

    @property作用: python的@property是python的一种装饰器,是用来修饰方法的. 我们可以使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同 ...

  5. python property函数_Python内置函数property()如何使用

    代码 class Shuxing(): def __init__(self, size = 10): self.size = size def getSize(self): print('getSiz ...

  6. Python·@property属性

    一.property属性 property属性可以用来给属性添加约束,比如温度属性,我们不允许低于-273度:成绩属性,我们不允许0分以下等等.而且使用property属性,将来修改约束条件的时候也很 ...

  7. Python property函数:定义属性

    如果为 Python 类定义了 getter.setter 等访问器方法,则可使用 property() 函数将它们定义成属性(相当于实例变量). property() 函数的语法格式如下: prop ...

  8. Python @property 详解

    Python 有一个概念叫做 property,它能让你在 Python 的面向对象编程中轻松不少.在了解它之前,我们先看一下为什么 property 会被提出. 一个简单的例子 比如说你要创建一个温 ...

  9. Python @property 用法

    本文整理自<Effective Python 编写高质量 Python 代码的 59 个有效方法>第 29 条:用纯属性取代 get 和 set 方法. Python 类 public 属 ...

最新文章

  1. 厉害了,用Python绘制动态可视化图表,并保存成gif格式
  2. 脉冲神经网络_【强基固本】脉冲神经网络(SNN)
  3. C#中Lock关键字的使用
  4. Open vSwitch系列实验(一):Open vSwitch使用案例扩展实验
  5. 利用JDBC连接Oracle数据库
  6. 【学习笔记】浅谈广义矩阵乘法——动态DP
  7. P2261-[CQOI2007]余数求和【数论,约数】
  8. 2018-2019 ACM-ICPC Nordic Collegiate Programming Contest (NCPC 2018) - 4.28
  9. Oracle中row_number()、rank()、dense_rank() 的区别
  10. 《剑指Offer》 二叉树的深度
  11. OpenShift 4 - 为Serivce Account赋权
  12. 第一次冲刺团队绩效评估
  13. 2018阿里文学春招面试题
  14. 三思而行 --jsp基础篇
  15. 网页中自动连续播放音乐文件的实现
  16. 计算机学院宣传橱窗,校园橱窗、报栏、展板、宣传标语管理办法
  17. 抖音小店入驻精选联盟有什么条件?精选联盟添加商品操作流程分享
  18. 零售ERP开发(一)
  19. 虚拟机在客户端和服务器之间存在时间,Server 2012 Domain Controller上出现“客户端和服务器之间存在时间和/或日期差异”错误...
  20. 小程序怎么搭建?学会这些技巧,开启创业之路

热门文章

  1. 芯原助力蓝洋智能部署基于Chiplet架构的芯片产品
  2. python对比柱状图_Python 数据分析测试5 之 柱状图对比显示
  3. 训练技巧《Must Know Tips/Tricks in Deep Neural Networks (by Xiu-Shen Wei)》学习笔记
  4. jpf java 是什么_JPF学习一
  5. SCM(供应链管理)的概念
  6. 关于JDK加密解密Key长度限制的三种解决方案
  7. spring快速入门
  8. office自动化,报错 ‘win32com.gen_py....‘ has no attribute ‘CLSIDToClassMap‘
  9. 写文章与写代码和书法作品与软件作品
  10. 弱小目标检测跟踪算法研究(5) 基于顶帽变换(Top_hat)算法的红外弱小目标检测之背景抑制