类---中装饰器的使用(实验楼学习笔记)

你可能想要更精确的调整控制属性访问权限,你可以使用 @property 装饰器,@property 装饰器就是负责把一个方法变成属性调用的。

例如:

#!/usr/bin/env python3

class Account(object):
    def __init__(self, rate):
        self.__amt = 0
        self.rate = rate

    @property
    def amount(self):
        return self.__amt

    @property
    def cny(self):
        return self.__amt * self.rate

    @amount.setter
    def amount(self, value):
        if value < 0:
            print("Sorry, no negative amount in the account.")
            return
        self.__amt = value

if __name__ == '__main__':
    acc = Account(rate=6.6)
    acc.amount = 20
    print("Dollar amount:", acc.amount)
    print("IN CNY:", acc.cny)
    acc.amount = -100
    print("Dollar amount:", acc.amount)
 

运行结果如下:

猜你喜欢

转载自blog.csdn.net/qq_39112101/article/details/84838518
今日推荐