class Person:
"""
属性私有化有两个好处,一是对属性进行隐藏,保护属性,二是可以对属性进行过滤
"""
def __init__(self):
# 让所有对象创建出来就具备了age=18的属性,并且此age属性,不能由外部直接访问
self.__age = 18
def getAge(self):
return self.__age
def setAge(self, value):
# 可以在这里进行属性过滤,年龄值在0到150之间的正整数
if isinstance(value, int) and 0 < value < 150:
self.__age = value
else:
print("设置的年龄有误!")
p = Person()
print(p.getAge())
p.setAge(20)
print(p.getAge())
p.setAge(-19)
print(p.getAge())
/Users/jun/anaconda3/envs/python36/bin/python /Users/jun/PycharmProjects/pyqt5/面向对象/属性私有化.py
18
20
设置的年龄有误!
20
Process finished with exit code 0
网友评论