propert应用
#方式一: # class Student(object): # def __init__(self,name,sc): # self.name = name # self.sc = sc # # @property # def score(self): # return self.sc # # @score.setter # def score(self,value): # if not isinstance(value, int): # raise ValueError('分数必须是整数才行呐') # if value < 0 or value > 100: # raise ValueError('分数必须0-100之间') # self.sc = value # # @score.deleter # def score(self): # del self.sc #----------------------------------------------------------- #方式二: class Student(object): def __init__(self,name,sc): self.name = name self.sc = sc def get_score(self): return self.sc def set_score(self,value): if not isinstance(value, int): raise ValueError('分数必须是整数才行呐') if value < 0 or value > 100: raise ValueError('分数必须0-100之间') self.sc = value def del_score(self): del self.sc score = property(get_score,set_score,del_score) X = Student('anec',50) print(X.__dict__) print(X.score) X.score = 90 print(X.score) del X.score print(X.__dict__)