参考:@property
NOTE
1.在绑定参数时,为了避免对属性不符合逻辑的操作,需要对传入的参数进行审核。
#!/usr/bin/env python3
class MyClass(object):
"""docstring for MyClass"""
def __init__(self):
super(MyClass, self).__init__()
def set_Attr(self, score):
if score >= 0 and score <= 100:
self.score = score
else:
raise ValueError('Attribute Setting Error')
def get_Attr(self):
return self.score
def main():
A = MyClass()
A.score = 59
print(A.get_Attr())
A.set_Attr(101)
print(A.get_Attr())
if __name__ == '__main__':
main()
59
Traceback (most recent call last):
File "./oop9.py", line 26, in <module>
main()
File "./oop9.py", line 22, in main
A.set_Attr(101)
File "./oop9.py", line 12, in set_Attr
raise ValueError('Attribute Setting Error')
ValueError: Attribute Setting Error
普通的做法是,调用对象的方法传入参数并设置,但是这样看上去又过于繁琐。
2.Python内置的@property装饰器负责把一个方法变成属性进行调用:
class Student(object):
"""docstring for Student"""
def __init__(self):
super(Student, self).__init__()
@property
def score(self): # turn into an attribute
return self.score
@score.setter
def score(self, val):
if val >= 0 and val <= 100:
self.score = val
else:
raise ValueError('Attribute Setting Error')
RecursionError: maximum recursion depth exceeded in comparison
把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值。
getter => Attribute => create setter
3.还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:
class Student(object):
"""docstring for Student"""
def __init__(self):
super(Student, self).__init__()
@property
def score(self): # turn into an attribute
return self.score
此时Attribute score就是一个只读属性。无法对其进行设置或赋值。
2017/3/3