propertyプロパティのPython実装の二種類

propertyプロパティのPython実装の二種類

この方法の一つ

class Money(object):
    
    def __init__(self):
        self.__money = 0
    
    def get_money(self):
        return self.__money
    
    def set_money(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error: 不是整型数字")
    
    # 定义一个属性, 当设置这个属性 调用 set_money 方法, 当获取值时 调用get_money 方法
    money = property(get_money, set_money)
a = Money()

a.money = 100   # 调用 set_money 方法

print(a.money)  # 调用 get_money 方法

方法二

class Money(object):
    
    def __init__(self):
        self.__money = 0
    
    # 使用装饰器 property 进行修饰, 当获取属性时 调用以下函数
    @property 
    def money(self):
        return self.__money
    
    # 使用装饰器 property 进行修饰, 当设置属性时 调用以下函数
    @money.setter
    def money(self, value):
        if isinstance(value, int):
            self.__money = value
        else:
            print("error: 不是整型数字")
a = Money()

a.money = 100   # 调用@property 修饰的方法

print(a.money)  # 调用@money.setter修饰的方法
公開された98元の記事 ウォンの賞賛2 ビュー3905

おすすめ

転載: blog.csdn.net/weixin_45875105/article/details/104611793