property装饰器:将一个函数功能伪装成一个数据属性
版本一:
class Foo: def __init__(self, name, age): self.__name = name self.age = age @property def name(self): return self.__name #obj.name访问的是self.__NAME(这也是真实值的存放位置) @name.setter def name(self, v): if type(v) is not str: print("必须是str类型") return self.__name = v @name.deleter def name(self): print("不能删除") obj = People('ly', 18) print(obj.name) print(obj.get_name) obj.set_name('EGON') obj.name = 'x' print(obj.name) del obj.name
版本二:
class People(): __country = 'CHINA' # _People__country def __init__(self, name, age): self.__name = name self.age = age def get_name(self): return self.__name def set_name(self, v): if type(v) is not str: print("必须是str类型") return self.__name = v def del_name(self): print("不能删除") # 这样写, 必须按照这个顺序 xxx = property(get_name, set_name, del_name) obj = People('ly', 18) print(obj.xxx) obj.xxx = 'EGON' print(obj.xxx) del obj.xxx