标签:class play 利用 object 技术 设值 ret desc display
1、为什么要用property属性?
答:用property属性可以很方便的取值和设值,以前都是用方法来实现的,用方法的话还得考虑参数等等,不方便。
2、如何设置property属性?
答:有两种方法:
1>利用装饰器:
1 class Food(object): 2 def __init__(self): 3 self.old_price = 100 4 self.discount = 0.8 5 6 @property 7 def price(self): 8 new_price = self.old_price * self.discount 9 return new_price 10 11 @price.setter 12 def price(self, value): 13 self.old_price = value 14 15 @price.deleter 16 def price(self): 17 del self.old_price 18 19 obj = Food() 20 obj.price 21 obj.price = 200 22 del obj.price
2>利用类属性:
1 class Food(object): 2 def __init__(self): 3 self.old_price = 100 4 self.discount = 0.8 5 6 def get_price(self): 7 new_price = self.old_price * self.discount 8 return new_price 9 10 def set_price(self, value): 11 self.old_price = value 12 13 def del_price(self): 14 def self.old_price 15 16 17 18 19 PRICE = property(get_price, set_price, del_price, "description...") 20 21 obj = Food() 22 obj.price 23 obj.price = 200 24 del obj.price
标签:class play 利用 object 技术 设值 ret desc display
原文地址:https://www.cnblogs.com/eric818/p/10201190.html