倒霉的程序员SA新建了这样一个简单的
Student
类:class Student: def __init__(self, score = 0): self.score = score
然后各种使用这个
Student
类:s1 = Student() s1.score = 100 s2 = Student() s2.score = 90 s3 = Student() s3.score = 59 s4 = Student() s4.score = -50 print(s1.score) print(s2.score) print(s3.score) print(s4.score)
后来SA在使用过程中发现,这样不行啊,怎么负数也可以,然后他把
Student
改造了一下:class Student: def __init__(self, score = 0): self._score = score def get_score(self): return self._score def set_score(self, value): if not isinstance(value, int): raise ValueError("score must be an interger!") if value < 0 or value > 100: raise ValueError("score must between 0~100!") self._score = value
他得意洋洋地说,我这里用
_score
代替score
是想告诉后来人:我不建议他直接调用_score
属性。我们像下面这样用就可以规避别个乱入score
啦:s1 = Student() s1.set_score(100) print(s1.get_score())
后来SA发现,我去,要修改的地方太多啦!有没有更好的办法?还好他看到了廖雪峰的官方网站,原来还有
@property
这样神奇的用法:class Student: def __init__(self, score = 0): self._score = score @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError("score must be an interger!") if value < 0 or value > 100: raise ValueError("score must between 0~100!") self._score = value
这样,我原来写的那些代码不用修改就可以直接使用啦:
s1 = Student() s1.score = 100 s2 = Student() s2.score = 90 s3 = Student() s3.score = 59 s4 = Student() s4.score = -50 print(s1.score) print(s2.score) print(s3.score) print(s4.score)
- SA顿生感慨,有时间还是得多看看廖雪峰的官方网站啊!
@property的妙用
最新推荐文章于 2023-04-14 14:39:38 发布