有时候我们不想外界修改属性值,那么通过将属性修饰器@property放在方法的上方创建属性函数。这意味着当访问同名的实例属性时,将调用该方法。
class Pizza:
def __init__(self, toppings):
self.toppings = toppings
@property # 属性装饰器
def pineapple_allowed(self):
return False
pizza = Pizza(["cheese", "tomato"])
print(pizza.pineapple_allowed)
pizza.pineapple_allowed = True
---------------------------
运行结果
False
Traceback (most recent call last):
File "D:/software/learn_python/learn_python/Day1/属性函数.py", line 12, in <module>
pizza.pineapple_allowed = True
AttributeError: can't set attribute
可以看到这里是不能修改属性
网友评论