如下Dog类有一个birthday属性,它的取值要大于1900年 ,这时候@property装饰器就派上了用场 。主要有两步:首先,@property装饰birthday方法;其次,使用@birthday.setter装饰器再装饰birthday ,传入的value若小于等于1900,就会抛出ValueError的异常。
class Dog:def __init__(self, name, birthday):self.name = nameif birthday <= 1900:raise ValueError("出生早于1900年")self._birthday = birthday # 带有前置下划线标志着仅类内使用@propertydef birthday(self):print("正在获取出生年份...")return self._birthday@birthday.setterdef birthday(self, value):"""对外单独给属性birthday赋值时有用"""if value <= 1900:raise ValueError("出生早于1900年")self._birthday = valuehsq = Dog(name='hsq', birthday=2020)# 访问birthday属性print(hsq.birthday)# 修改birthday属性hsq.birthday = 1860
使用@property装饰器来修饰方法,使之成为属性。
上面程序中使用@property修饰了birtyday()方法,这样就使得该方法变成了birthday属性的getter方法。如果只有该方法,那么birthday属性只是一个只读属性。
当程序使用@property修饰了birthday属性之后,又多出一个@birthday.setter装饰器,该装饰器用于修饰birthday属性的setter方法,如上面程序中第13行代码所示。这样birthday属性就有了getter和setter方法,birthday属性就变成了读写属性。
