zoukankan      html  css  js  c++  java
  • python的私有变量解析

    在内的内部定义并使用,外部无法訪问,以双下划线作为前作,定义后被python转为
    _classname__变量名了

    --------------------------------------------------------------------------------------
    In [1]: class aa:
       ...: __x = 12 #私有变量_ _x
       ...: def px(self):
       ...: print 'private __x', aa.__x #内部訪问
       ...:

    In [2]: a = aa()

    In [3]: a.px()
    private __x 12

    In [4]: dir(a)
    Out[4]: ['__doc__', '__module__', '_aa__x', 'px'] # map成_classname__变量名了

    In [5]: a.__x = 13#实例对象a的实例变量

    In [6]: dir(a)
    Out[6]: ['__doc__', '__module__', '__x', '_aa__x', 'px']

    In [7]: print a.__x
    13

    In [8]:In [8]: print aa.__x
    ---------------------------------------------------------------------------
    AttributeError Traceback (most recent call last)
    <ipython-input-8-34f87438b5b5> in <module>()
    ----> 1 print aa.__x

    AttributeError: class aa has no attribute '__x'

    In [9]:
    -----------------------------------------------------------
  • 相关阅读:
    python3 练习题 day04
    python3 装饰器
    python3 生成器和生成器表达式
    python3 列表/字典/集合推导式
    python3 迭代器
    python3 day04 大纲
    ES6 的数值扩展
    ES6中的解构赋值
    ES6中 let与const 的区别
    react的基本配置安装及使用babel
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3801255.html
Copyright © 2011-2022 走看看