取值和赋值
class Actress():
def __init__(self):
self.name = 'TianXin'
self.age = 5
类Actress
中有两个成员变量name
和age
。在外部对类的成员变量的操作,主要包括取值和赋值。简单的取值操作是x=object.var
,简单的赋值操作是object.var=value
。
>>> actress = Actress()
>>> actress.name #取值操作
'TianXin'
>>> actress.age #取值操作
20
>>> actress.name = 'NoName' #赋值操作
>>> actress.name
'NoName'
使用 Getter 和 Setter
上述简单的取值和赋值操作,在某些情况下是不能满足要求的。比如,如果要限制Actress
的年龄范围,那么只使用上述简单的赋值操作就不能满足要求了。getter
和setter
实现这样的要求。
class Actress():
def __init__(self):
self._name = 'TianXin'
self._age = 20
def getAge(self):
return self._age
def setAge(self, age):
if age > 30:
raise ValueError
self._age = age
调用setAge
函数可以实现将变量_age
的取值范围限制到小于30.
>>> actress = Actress()
>>> actress.setAge(28)
>>> actress.getAge()
28
>>> actress.setAge(35)
ValueError
使用property
property的定义是
class property(object)
property(fget=None, fset=None, fdel=None, doc=None) -> property attributefget is a function to be used for getting an attribute value, and likewise, fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x
其中,fget
是取值函数,fset
是赋值函数,fdel
是删除函数。使用property也实现上述对成员变量的取值限制。
class Actress():
def __init__(self):
self._name = 'TianXin'
self._age = 20
def getAge(self):
return self._age
def setAge(self, age):
if age > 30:
raise ValueError
self._age = age
age=property(getAge, setAge, None, 'age property')
经过上面的定义后,可以像简单取值和赋值操作一样操作age
。比如,
>>> actress = Actress()
>>> actress.age
20
>>> actress.age = 18
>>> actress.age = 55
ValueError
使用@property
使用@property同样可以实现上述类的定义。
class Actress():
def __init__(self):
self._name = 'TianXin'
self._age = 20
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if age > 30:
raise ValueError
self._age = age
使用时的示例:
>>> actress = Actress()
>>> actress.age
20
>>> actress.age = 18
>>> actress.age = 45
ValueError
Python2 和 Python3中使用property的区别
上述property示例在Python3的环境下有效。在Python2中,使用property时,类定义时需要继承object
。否则,property的赋值操作不可使用。
Python2下property的正确使用方式:
class Actress(object): #差别在这里
def __init__(self):
self._name = 'TianXin'
self._age = 20
@property
def age(self):
return self._age
@age.setter
def age(self, age):
if age > 30:
raise ValueError
self._age = age
def setName(self, name):
self._name = name
def getName(self):
return self._name
def delName(self):
print('Goodbye...')
del self._name
name = property(getName, setName, delName, 'name property')
网友评论