结束
下面代码中,创建Student类,该类中有score属性,即分数,代码如下:
class Student:
def __init__(self):
self.score=100
提出问题
分数有最高分(如100),最低分(0分),如果直接设置分数,可能会造成不正确的分值,代码如下:
xiaoming=Student()
xiaoming.score=120
xiaoming.score=-5
print(xiaoming.score)
解决
将实例属性设置为私有,增加set方法,并在set方法中做分值校验,并增加get方法,获取分支
class Student:
def __init__(self):
self.__score=100#属性名前面加两个下划线表示私有
def set_score(self,score):
if type(score)==int:
if 0<=score and score<=100:
self.__score=score
else:
raise ValueError("score必须大于等于0,小于等于100")
else:
raise TypeError("score必须是int类型")
def get_score(self):
return self.__score
xiaoming=Student()
xiaoming.set_score(-10)
xiaoming.set_score(120)
xiaoming.set_score(10)
print("xiaoming的分数:%d"%xiaoming.get_score())
总结
面向对象编程的特征之一是封装,将类中属性设置为私有,不能直接设置、访问属性,而是通过set、get方法。