改变类的私有变量的值有2种方法:

间接:为这个私有变量提供一个操作的方法,如:def get_score(self, score)

直接:实例名._类名__私有变量名 = 值, 如:f._Student__score = 10


间接

#!/usr/bin/python#-*-coding:utf-8-*-classStudent(object):def__init__(self,name,score):self.__name=nameself.__score=scoredefset_score(self,score):ifscore<11:print"false"returnFalseself.__score=scorereturnself.__scoredefget_score(self):returnself.__scoref=Student('hah',11)printf.get_score()f.set_score(12)printf.get_score()

运行结果:

1112


2.直接

#!/usr/bin/python#-*-coding:utf-8-*-classStudent(object):def__init__(self,name,score):self.__name=nameself.__score=scoredefset_score(self,score):ifscore<11:print"false"returnFalseself.__score=scorereturnself.__scoredefget_score(self):returnself.__scoref._Student__score=13printf.get_score()

运行结果:

13