Python中property函数用法实例分析

yipeiwu_com7年前Python基础

本文实例讲述了Python中property函数用法。分享给大家供大家参考,具体如下:

通常我们在访问和赋值属性的时候,都是在直接和类(实例的)的__dict__打交道,或者跟数据描述符等在打交道。但是假如我们要规范这些访问和设值方式的话,一种方法是引入复杂的数据描述符机制,另一种恐怕就是轻量级的数据描述符协议函数Property()。它的标准定义是:

+ property(fget=None,fset=None,fdel=None,doc=None)
+ 前面3个参数都是未绑定的方法,所以它们事实上可以是任意的类成员函数

property()函数前面三个参数分别对应于数据描述符的中的__get____set____del__方法,所以它们之间会有一个内部的与数据描述符的映射。

综上描述,其实property()函数主要是用来规范化访问类的属性和修改类属性的值的一种方法。

property()函数可以用0,1,2,3,4个参数来调用,顺序依次是get,set,del,doc,这四个。

property()的实现方法有两种,见代码

第一种:

#!/usr/bin/python
#coding: utf-8
class Rectangle(object):
  def __init__(self, width, height):
    self.width = width
    self.height = height
  def getSize(self):
    return self.width, self.height
  def setSize(self, size):
    self.width, self.height = size
  def delSize(self):
    del self.height
  size = property(getSize, setSize, delSize, "实例对象")
r = Rectangle(10, 20)
# 输出此时矩形的长和宽
# 此时执行的是getSize
print r.size
# 修改size的值
# 此时执行的是setSize
r.size = 100, 200
print r.size
del r.height
print r.width
# height属性已经被删除,下面语句会报错
# print r.size

运行结果:

(10, 20)
(100, 200)
100

第二种:(装饰器)

#!/usr/bin/python
#coding: utf-8
class Rectangle(object):
  def __init__(self, width, height):
    self.width = width
    self.height = height
  # 下面加@符号的函数名要相同
  # 第一个是get方法
  @property
  def Size(self):
    return self.width, self.height
  # 此处是set方法,是@property的副产品
  @Size.setter
  def Size(self, size): # 此时接收的是一个元祖
    self.width, self.height = size
  @Size.deleter
  def Size(self):
    del self.width
    del self.height
r = Rectangle(10, 20)
print r.Size
r.Size = 100, 200
print r.Size
del r.height
# 由于上一步删除了self.height属性,所以下面再访问的时候会报错
# print r.Size
# 可以访问width,还没有被删除
print r.width

运行结果:

(10, 20)
(100, 200)
100

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

pycharm设置注释颜色的方法

操作方法如下所示: File-->Settings-->Editor-->Color&Fonts-->LanguageDefaults-->Linecomm...

Python的Django框架中消息通知的计数器实现教程

故事的开始:.count() 假设你有一个Notification Model类,保存的主要是所有的站内通知: class Notification(models.Model):...

Python列表list内建函数用法实例分析【insert、remove、index、pop等】

Python列表list内建函数用法实例分析【insert、remove、index、pop等】

本文实例讲述了Python列表list内建函数用法。分享给大家供大家参考,具体如下: #coding=utf8 ''''' 标准类型函数: cmp():进行序列比较的算法规则如下:...

Python字符串格式化%s%d%f详解

关于讨论输出格式化的问题,小编不是一时兴起,之前学习python的时候就经常遇到输出时“%d”,一直没有仔细学习,今天又看到了,下面分享一个简单实例,python输出99乘法表: #...

python-pyinstaller、打包后获取路径的实例

python-pyinstaller、打包后获取路径的实例

使用pyinstaller可以把.py文件打包为.exe可执行文件,命令为: pyinstaller hello.py 打包后有两个文件夹,一个是dist,另外一个是build,可执行文...