python入门(@property,@*.setter)

来源:互联网 发布:mac的usb不支持 编辑:程序博客网 时间:2024/06/10 18:52
@property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
1、只有@property表示只读
2、同时有@property和@*.setter表示可读可写

3、同时有@property和@*.setter和@*.deleter表示可读可写可删除


代码:

  1 #coding=utf-8  2 class student(object):  #需继承父类object,否则property等无法生效   3   4     def __init__(self,v_id = '000'):  5         self.__id = v_id  6   7     @property  8     def score(self):  9         return self._score 10  11     @score.setter 12     def score(self,v_score): 13         if not isinstance(v_score,int): 14             raise ValueError('score must be an integer!') 15         if v_score < 0 or v_score > 100: 16             #raise ValueError('score must between 0 and 100')      17             print('数值不在有效范围内') 18         else: 19             print(v_score,'operation success') 20         self._score = v_score 21  22     @property 23     def get_id(self): 24         return self.__id 25  26 s = student('001') 27 s.score=60 28 #print s.__id   #报错,没有该属性 29 print s.get_id 30 print s.score 31  32 s = student() 33 s.score=-100 34 print s.get_id 35 print s.score

执行:


阅读全文
0 0
原创粉丝点击