我们定义一个金钱的类,有美元和美分的属性。
class Money:
def __init__(self, dollars, cents):
self.dollars = dollars
self.cents = cents
我们可以对它进行实例化,并更改属性的值。
>>> money = Money(10,100)
>>> money.cents
100
>>>money.dollars
10
>>> money.cents += 100
>>> money.dollars += 10
>>> money.cents
200
>>> money.dollars
20
现在为了调用更方便,我们需要把金钱统一成美分的单位,而其他依赖该程序不能受影响。
我们可以使用@property
重构代码,我们用它装饰类,一个类里定义的方法一旦被@property修饰,你可以像使用属性一样去使用这个方法。
class Money:
def __init__(self, dollars, cents):
self.dollars = dollars
self.cents = cents
@property
def total_cents(self):
t_cents = self.dollars * 100 + self.cents
return t_cents
@total_cents.setter
def total_cents(self,t_cen):
self.dollars += t_cen // 100
self.cents += t_cen
money = Money(10,20)
print(money.cents)
print(money.dollars)
print(money.total_cents)
money.total_cents = 100
print(money.cents)
print(money.dollars)
print(money.total_cents)
#输出
#20
#10
#1020
#120
#11
#1220
@total_cents.setter
让我们可以直接去设置total_cents
属性,从而改变cents
和dollars
的值。
如果还有些不明白的小伙伴,可以参考下面的文档。
参考文档:
快速重构Python代码:利用@property装饰器
http://www.coolpython.net/python_senior/senior_oop/propery_reconsitution.html