一、什么是特性property
将函数属性伪装成数据属性。
将原本访问的函数: .函数名()伪装成 .函数名
伪装前:
class People: def __init__(self, name, weight, height): self.name = name self.weight = weight self.height = height def bmi(self): return self.weight / self.height obj = People('link', 80, 1.8) print(obj.bmi())
伪装后:
@property def bmi(self): return self.weight / self.height
obj = People('link', 80, 1.8) print(obj.bmi)
只要property伪装过的属性都会有setter,getter,deleter函数
伪装可改为:
class People: def __init__(self, name): self.__name = name @property def name(self): return self.__name @name.setter def name(self, name): self.__name = name @name.deleter def del_name(self): del self.__name
这样做的好处,可以针对属性进行管理和约束。还可以另外一种写法:定义好get,set,del函数。
class People: def __init__(self, name): self.__name = name def get_name(self): return self.__name def set_name(self, name): self.__name = name def del_name(self): del self.__name name = property(get_name, set_name, del_name)