在学习Python的过程中发下,它把类(class)中所有的成员函数和成员变量都看做是"Public"的,作为C++出身的程序员们可能就不习惯了。
Python的官方教程中如是说:““Private” instance variables that cannot be accessed except from inside an object don’t exist in Python.”。也就是说,在Python中我们不能够像C++或者Java那样有专门的private和public关键字来指定某些成员是公有的,哪些成员是私有的。
然而,Python教程中又说了:“However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam)
should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.”。
OK,原来在Python中大家都是通过在一个变量或者函数之前加上下划线来表示私有变量的,例如__spam(这里是两个下划线)就是私有的。
同时,Python为了保证不能再class之外访问该变量,“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.”,意思就是说,Python会在类的内部自动的把你定义的__spam变量的名字替换成为 _classname__spam(注意,classname前面是一个下划线,spam前是两个下划线),Python把这种技术叫做“name mangling”。因此,用户在外部访问__spam的时候就会提示找不到相应的变量。
下面给出一段简单的代码: