property函数

 __metaclass__=type

 class Rectangle:
     def __init__(self):
             self.width=0
             self.height=0
     def setSize(self,size):
             self.width,self.height=size
     def getSize(self):
             return self.width,self.height

  size=property(getSize,setSize)

>>>r=Rectangle()

>>>r.width=10

>>>r.height=5

>>>r.size

(10,5)

>>>r.size=150,100

>>>r.width

150

property函数可以用0、1、3或者4个参数来调用,如果没有参数,产生的属性既不可读,也不可写。如果只使用一个参数调用(一个取值方法),产生的属性是制度的,第三个参数(可选)是一个用于删除特性的方法(它不要参数)。第四个参数(可选)是一个文档字符串。分别叫做fget,fset,fdel和doc,如果想要一个属性是只写的,并且有一个文档字符串,可以使用关键字参数的方式来实现

property这个函数很重要,理论上说,在新式类中应该使用property函数而不是访问器方法

原文地址:https://www.cnblogs.com/yhcreak/p/5378711.html