class Person(object):
"""
目的:让外界只可以读取,不能修改
"""
def __init__(self):
# 首先将属性设置为外界既不能读取也不能修改
self.__age = 18
# 然后提供方法让外界读取,只提供读方法,不提供写方法
# @property装饰器的作用是让方法以属性的形式提供给外界调用
@property
def age(self):
return self.__age
p = Person()
print(Person().age)
# 外界尝试修改age,则会报错
p.age = 10
/Users/jun/anaconda3/envs/python36/bin/python /Users/jun/PycharmProjects/pyqt5/面向对象/只读属性.py
18
Traceback (most recent call last):
File "/Users/jun/PycharmProjects/pyqt5/面向对象/只读属性.py", line 19, in <module>
p.age=10
AttributeError: can't set attribute
Process finished with exit code 1
网友评论