[深入Python]Python的私有变量

Python没有真正的私有变量。内部实现上,是将私有变量进程了转化,规则是:_<类名><私有变量>

下面的小技巧可以获取私有变量:

1 class Test(object):

2     def __init__(self):

3         self.__zzz=111

4 

5 if __name__ == '__main__':

6     a =  Test()

7     print a._Test__zzz

同样,通过a._Test__zzz=222的方式,可以修改私有变量的值。

通过dir(Test)和dir(a)可以看到类属性和其实例属性之间的区别:

print dir(Test)

print dir(a)

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

['_Test__zzz', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

 

 

你可能感兴趣的:(python)