# property: import math class Circle(object): def __init__(self, r): self.r = r @property # 把一个方法伪装成一个属性,调用这个方法时不需要加括号就直接得到返回值 def area(self): return math.pi * self.r**2 c = Circle(5) print(f'半径:{c.r}, 面积:{c.area}') import time class Person(object): def __init__(self, name, birth): self.name = name self.birth = birth @property def age(self): # 所以装饰的这个方法不能有参数 return time.localtime().tm_year - self.birth TB = Person('太白', 1998) print(TB.age) # property的第二个应用场景:和私有属性合作的 class User(object): def __init__(self, user, pwd): self.user = user self.__pwd = pwd @property def pwd(self): return self.__pwd alex = User('alex', 123) print(alex.pwd) # property进阶: class Goods(object): discount = 0.8 def __init__(self, name, oringin_price): self.name = name self.__price = oringin_price @property def price(self): return self.__price * self.discount @price.setter def price(self, new_price): print('调用我了---') if isinstance(new_price, int): self.__price = new_price @price.deleter def price(self): print('执行我了') del self.__price apple = Goods('apple', 5) print(apple.price) # 查看被@property装饰的price函数 apple.price = 10 # 调用的是被setter装饰的price print(apple.price) # del apple.price # 调用的是被deleter装饰的price,而这里只是调用方法,要在方法内部执行删除 # print(apple.price)