属性函数---setter/getter

属性函数同样可以使用setter/getter设置读写方法。

setter函数定义设置属性的值。getter函数定义获得属性的值。

要定义属性值的函数,使用属性名后面跟着.setter关键词,同样.getter定义了这个方式属于获取属性值的函数。

class Pizza:
    def __init__(self, toppings):
        self.toppings = toppings
        self._pineapple_allowed = False

    @property
    def pineapple_allowed(self):
        return self._pineapple_allowed

    # 设置属性值
    @pineapple_allowed.setter
    def pineapple_allowed(self, value):
        if value:
            password = input("Enter the password:")
            if password =="111222333":
                self._pineapple_allowed = value
            else:
                raise ValueError("Alert! Intruder!")

    #  获取属性的值
    @pineapple_allowed.getter
    def get_value(self):
        return self._pineapple_allowed


pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = "这是值"
print(pizza.pineapple_allowed)
print(pizza.get_value)

运行结果

C:\ProgramData\Anaconda3\python.exe D:/software/learn_python/learn_python/Day1/属性函数.py
False
Enter the password:111222333
这是值
这是值

你可能感兴趣的:(属性函数---setter/getter)