【3.7】数据封装和私有属性

  • 在Python中,实例属性如果以双下划线开头,那么这个属性就是一个私有属性

 1 class Test:
 2     def __init__(self, x):
 3         self.__x = x
 4 
 5     def the_print(self):
 6         print(self.__x)
 7 
 8 
 9 t = Test(1)
10 print(t.__x)
11 t.the_print()
Traceback (most recent call last):
  File "demo.py", line 14, in <module>
    print(t.__x)
AttributeError: 'Test' object has no attribute '__x'

  但是,Python实现这种私有属性的方法,仅仅是通过改变该变量的名称来达到的

 1 class Test:
 2     def __init__(self, x):
 3         self.__x = x
 4 
 5     def the_print(self):
 6         print(self.__x)
 7 
 8 
 9 t = Test(1)
10 print(t.__dir__())
11 print(t._Test__x)
12 t.the_print()
['_Test__x', '__module__', '__init__', 'the_print', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__',
'__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']
1
1

  __x --> _Test__x

posted @ 2019-07-24 15:52  _simpleSmile  阅读(235)  评论(0编辑  收藏  举报