zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    静态文件
    orm多表操作
    thinkphp5.0模块设计
    thinkphp5.0URL访问
    thinkphp5.0入口文件
    thinkphp5.0生命周期
    thinkphp5.0架构总览
    thinkphp5.0目录结构
    thinkphp5.0开发规范
    thinkphp5.0安装
  • 原文地址:https://www.cnblogs.com/zydeboke/p/11238539.html
Copyright © 2011-2022 走看看