Python中@property的粗略理解
代码:# -*- coding:utf-8 -*-#!/usr/bin/env pythonclass Student(object):@propertydef get_score(self):return self._score@get_score.setterdef set_score(self, value):...
·
代码:
# -*- coding:utf-8 -*-
#!/usr/bin/env python
class Student(object):
@property
def get_score(self):
return self._score
@get_score.setter
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
注意:这里 s.get_score 而不是 s.get_score()
@property
装饰器把get_score方法变成属性调用
而在set_score方法上加上@get_score.setter意思是get_score方法中的属性是通过set_score来设置的
更多推荐
已为社区贡献1条内容
所有评论(0)