Python关于私有变量的问题?

class Student(object): def __init__(self, name, score): self.name = name self.__score = score def set_score(self, score): self.__score = score def get_score(self): return self.__score def print_score(self): print('%s: %s' % (self.name, self.__score)) bart = Student('Bart Simpson', 63) bart.__score = 100 # 设置__score变量 print(bart.__score) Python初学者,对于一些问题有点疑惑,…
关注者
13
被浏览
1600

我们来看看定义吧,官方文档:

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

关键是最后这一句,意思是指“只要该标识符出现在类的定义内,便会被解释器从文面上替换为_classname__name”。

而你的代码中显示的,__score是一个在运行时添加的变量,并未出现在类的定义中,所以名字没有被替换成上述形式。实际上Python并不存在真正的私有成员变量,只是命名上的共识而已。