Python中property函数用法实例分析

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python 对输入的数字进行排序的方法

要求,输入一串数字,并以列表的形式打印出来。 number = input('请输入一串数字:') print(number) print(type(number)) 假设输...

详解python单例模式与metaclass

单例模式的实现方式 将类实例绑定到类变量上 class Singleton(object): _instance = None def __new__(cls, *args...

python装饰器初探(推荐)

一、含有一个装饰器 #encoding: utf-8 ############含有一个装饰器######### def outer(func): def inner(*args...

Python创建普通菜单示例【基于win32ui模块】

Python创建普通菜单示例【基于win32ui模块】

本文实例讲述了Python创建普通菜单的方法。分享给大家供大家参考,具体如下: 一、代码 # -*- coding:utf-8 -*- #! python3 import win32...

归纳整理Python中的控制流语句的知识点

程序流 Python 解释器在其最简单的级别,以类似的方式操作,即从程序的顶端开始,然后一行一行地顺序执行程序语句。例如,清单 1 展示了几个简单的语句。当把它们键入 Python 解释...