Python学习(十三)--@property和property函数
- @property
@property装饰器可以把一个方法变成属性调用。
举一个例子,对学生成绩进行设置和查询。通过set_score来设置成绩,get_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
然后通过@property装饰器重新修改后:
class Student(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 >>> s = Student() >>> s.score = 60 # OK,实际转化为s.set_score(60) >>> s.score # OK,实际转化为s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
把一个getter方法变成属性,只需要加上@property。@property本身又创建了另外一个装饰器@score.setter,把一个setter方法变成属性赋值。
- property函数
property函数的原理和@property很相似,它有四个参数。
property(fget=None, fset=None, fdel=None, doc=None)
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 score = property(fget=get_score, fset=set_score) >>> s = Student() >>> s.score = 60 # OK,实际转化为s.set_score(60) >>> s.score # OK,实际转化为s.get_score() 60 >>> s.score = 9999 Traceback (most recent call last): ... ValueError: score must between 0 ~ 100!
参考: