@property装饰器是将方法可以像属性一样被调用
作为程序设计员,要考虑到用户输入不合理的数据时会提醒错误
- 普通程序,使用set和get来判断数据的合理性
class Student:
def __init__(self,age):
self.__age=age
def get_age(self):
return self.__age
def set_age(self,age):
if age>0:
self.__age=age
else:
print('输入错误')
c1=Student(18)
c1.set_age(20) #修改年龄
print(c1.get_age())
c1.set_age(-10) #修改年龄
print(c1.get_age())
- 使用@property和setter来判断数据的合理性
class Student:
def __init__(self,age):
self.__age=age
@property
def age(self):
return self.__age
@age.setter
def age(self,age):
if age>0:
self.__age=age
else:
print('输入错误')
c2=Student(20)
c2.age=18
print(c2.age)
c2.age=-10
print(c2.age)