""" """ __author__ = 'shaozhiqi' # 绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单, # 但是,没办法检查参数,导致可以把参数随便改 # 比如想限制student score的范围 class Student(object): def get_score(self): return self._score def set_score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value s = Student() s.set_score(60) print(s.get_score()) # 60 # print(s.set_score(1000)) # ValueError: score must between 0 ~ 100! # ---------------------property------------------------------------- # 上述方法不太简洁,使用property 修改 # @property装饰器就是负责把一个方法变成属性调用,默认是只读 class Student1(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score must be an integer!') if value < 0 or value > 100: raise ValueError('score must between 0 ~ 100!') self._score = value s1 = Student1() s1.score = 60 # s1.score = 9999999 # ValueError: score must between 0 ~ 100! # 报错说明里面有set 方法的实现,如果直接暴露的属性,就不会报错 # 只读属性------------------------------------------------------- class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self): return 2019 - self._birth # birth 是一个可读写属性,而age是一个只读属性 # age的值可以根据birth计算 s = Student() s.birth = 1990 print(s.birth) # 注意如果不赋值直接读 会error # s.age=100 # error AttributeError: can't set attribute property 默认是只读 print(s.age) # 29