如下这段python代码,自定义类Student用到了property装饰器。
很明显,我想要的效果是年龄大于等于18岁即不能设置,打印“输入的年龄不合法”的提示信息
class Student:
def __init__(self,age):
self.__age=age
# if isinstance(age, int) and age < 18:
# self.__age = age
# else:
# print('输入的年龄不合法')
@property
def age(self):
return self.__age
@age.setter
def age(self,age):
if isinstance(age,int) and age<18:
self.__age=age
else:
print('输入的年龄不合法')
s1=Student(30)
print(s1.age)
s1.age=20
运行结果为:
30
输入的年龄不合法
使用s1.age=20进行赋值,可以按照预设调用setter,完成控制赋值。
但问题在于s1=Student(30),其构造函数中没有控制语句,所以在实例化时就不能起到控制作用。难道我要在构造函数中重复的写一遍if isinstance(age,int) and age<18:的控制语句吗。这样显得很多余,不够pythonic。请问有其他的更优雅的处理方式吗?