总结:
1). Python内置的@property装饰器就是负责把一个方法变成属性调用的;
2). @property本身又创建了另一个装饰器@state.setter,负责把一个
setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作.
3). @property广泛应用在类的定义中,可以让调用者写出简短的代码,
同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。
源代码应用范例: 让属性只读:
from datetime import date
# Read-only field accessors
@property
def year(self):
# year (1-9999)
return self._year
@property
def month(self):
# month (1-12)
return self._month
@property
def day(self):
# day (1-31)
return self._day
if __name__ == "__main__":
d = date(2019, 10, 10)
print(d.year)
print(d.month)
print(d.day)
# d.year = 2020 # 此处不成功, year是只读的
# del d.year # 此处不成功, year是只读的
print(d.year)
当调用property属性的时候,被其装饰的函数只能读,不能进行其他操作,但是若想在类外部对其进行其他的操作(可读可写可删除等)时,则要加property衍生的其他装饰函数,同时其他的装饰函数定义的函数方法要和property定义的一样。
例如:
class Rectangle(object):
@property
def width(self):
# 变量名不与方法名重复,改为true_width,下同
return self.true_width
@width.setter
def width(self, input_width):
self.true_width = input_width
@property
def height(self):
return self.true_height
@height.setter
#与property定义的方法名要一致
def height(self, input_height):
self.true_height = input_height
@height.deleter
def height(self):
del self.true_height
s = Rectangle()
# 与方法名一致
s.width =111
s.height = 456
print(s.width,s.height)