@property 重构代码


我们定义一个金钱的类,有美元和美分的属性。

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属性,从而改变centsdollars的值。


如果还有些不明白的小伙伴,可以参考下面的文档。

参考文档:
快速重构Python代码:利用@property装饰器
http://www.coolpython.net/python_senior/senior_oop/propery_reconsitution.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值