[D]python编程property()用法
本帖最后由 fibbery 于 2012-07-02 15:07:26 编辑 python 2.5版本:
#这个版本无法正确运行
__metaclass__ = type
class rectangle :
def __init__(self, arg_width=0, arg_height=0) :
self.width = arg_width
self.height = arg_height
def setItem( self, *value ) : #可接受元祖参数值
self.width, self.height = value
def getItem(self) :
return self.width, self.height
def delItem(self) :
del self.width
del self.height
size = property(getItem,setItem,delItem, "display rectangle property")
#这个版本可以通过size返回属性,但不能通过size设置属性:
>>> rect = rectangle()
>>> rect.width , rect.height = 10, 20
>>> rect.size
(10, 20)
>>> rect.size(100,200) #通过size设置width ,height时
Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
rect.size(100,200)
TypeError: 'tuple' object is not callable
>>> rect.size = 100, 200 #通过size设置width ,height时
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
rect.size = 100, 200
File "C:/Users/TOSHIBA/Desktop/TmpFile/PythonCode/property", line 10, in setItem
self.width, self.height = value
ValueError: need more than 1 value to unpack
>>> rect.size = (100,200) #通过size设置width ,height时
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
rect.size = (100,200)
File "C:/Users/TOSHIBA/Desktop/TmpFile/PythonCode/property", line 10, in setItem
self.width, self.height = value
ValueError: need more than 1 value to unpack
#这个版本可以正确运行
__metaclass__ = type
class rectangle :
def __init__(self, arg_width=0, arg_height=0) :
self.width = arg_width
self.height = arg_height
def setItem( self, tuple ) : #显示定义可接受元祖参数
self.width, self.height = tuple
def getItem(self) :
return self.width, self.height
def delItem(self) :
del self.width
del self.height
size = property(getItem,setItem,delItem, "display rectangle property")
#这个是《python基础教程》(第2版) 上148页的例题,也无法正确运行
__metaclass__ = type
class rectangle :
def __init__(self) :
self.width = 0
self.height = 0
def setItem( self, value ) :
self.width, self.height = value
size = property(getItem,setItem)
class C(object):
def __init__(self): self.__x = None
def getx(self): return self._x
def setx(self, value): self._x = value
def delx(self): del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
class Parrot(object):
def __init__(self):
self._voltage = 100000
@property
def voltage(self):
"""Get the current voltage."""
return self._voltage
def setItem( self, *value ) : #可接受元祖参数值
self.width, self.height = value
时,python也是要先把右侧的值pack起来,形成一个tuple,所以它等同于
rect.size = 100, 200
rect.size = (100,200)