python 特性属性
2018-10-20 本文已影响3人
dushuzhong
实现其它语言中拥有的getter和setter功能
作用:
用来模拟一个属性
通过@property 装饰器可以对模块属性的取值和赋值加以控制
示例见:
class Student:
def __init__(self, s):
self.__score__ = s
@property # 等价于property(get_score)
def score(self):
return self.__score__
@score.setter
def score(self,s):
assert 0 <= s <= 100, "报错"
self.__score__ = s
def get_score(self):
return self.__score__
def set_score(self,s):
assert 0 <= s <= 100, "报错"
self.__score__ = s
score = property(get_score)
s1 = Student(50)
print(s1.score)
s1.score = 10000
避免用户随意修改属性
但是可以通过 score = property(get_score,set_score) 这样就可以
print(s1.score)
s1.score = 70 实际上是添加实例变量
- python 方法名都是类变量