Python的私有变量实现是通过在变量名前加__实现的,即加两个下划线。

如下:

class Test:

    __x="hello"

当执行print(Test().__x)时,会报错:

Traceback (most recent call last):
  File "C:\Users\DELL\Desktop\test.py", line 12, in <module>
    print(Test().__x)
AttributeError: 'Test' object has no attribute '__x'

但实际上Python并不支持私有变量,只是内部会把有两个下划线的用另一个变量名代替:_Test_xx,即_<Class>__<Variable>

>>> print(Test()._Test__x)
hello