Python _X __all__ 模拟 导入'私有'变量 及其注意点和实例
2014-12-13 12:24
393 查看
开头是下划线的变量(如_X):
在特定的情况下,可以吧下划线放在变量名的签名(如_X)可以防止客户端使用from *语句导入模块名时,把其中的那些变量名复制出去;但是下划线不是'私有'声明:仍可以使用其他导入形式看见并且修改这类变量例如使用import__all__(语句)
此外也可以在模块顶层把变量名的字符串列表赋值给变量__all__以达到类似_X命名惯例的隐藏效果;使用此功能,from*语句只会把列在__all__列表中的这些变量名复制出来__all__是指出要复制的变量名,而_X时指出不要被复制的变量名;Python会先寻找模块内的__all__列表(如果定义__all__的时候,只会复制__all__内的变量名,不会复制开头没有下划线的变量名),如果没有定义的话,from * 就会复制出开头没有单下划线的所有变量名
__all__列表只对from *语句这种形式有效,并不是私有声明
例子:
#test.pykey='got'
_nooutpute='lllllllllllllll'
error='fasdfsa'
code='fsadfsa'
decode='324324'
__all__=['error','code','decode']
print {'already': (lambda :2+2),
'got':(lambda :2*4),
'one': (lambda :2**4)
}[key]()
#_X__all__.py
from test import *
print(error)
print(key)
注意点:
可以看出__all__中的必须是变量名,并且在引用之前一定要进行赋值#test.py更改测试__all__
error='fasdfsa'
code='fsadfsa'
decode='324324'
__all__=['error','code','decode','testname']
#_x__all__.py
from test import *
print(error)
print(testname)
相关文章推荐
- TypeError: 'module' object is not callable 原因分析(python模块导入注意事项)
- Python 中特殊变量/方法命名规则说明(特别是私有变量)及使用实例
- Python 私有变量、私有方法、类变量与实例变量
- Python 中特殊变量/方法命名规则说明(特别是私有变量)及使用实例
- python -- why defined '__new__' and '__init__' all in a class
- [python]用eval强制将字符串转换为字典变量时候出错:NameError: name 'null' is not defined[python]用eval函数 字符串转dict
- python实例2—NameError: name 'file' is not defined
- python模块以及导入出现ImportError: No module named 'xxx'问题
- python模拟登陆csdn及其注意事项,附带源码
- 四.OC基础--1.文档安装和方法重载,2.self和super&static,3.继承和派生,4.实例变量修饰符 ,5.私有变量&私有方法,6.description方法
- Python中关于模块的 '__name__' 变量的使用
- Eclipse CDT Ubuntu下重新导入工程后make: *** No rule to make target `all'. Stop.
- Python导入模块(包)的两种方式 TypeError: 'module' object is not callable
- 用变量来取得exec('')的标量返回值.
- [ZT]Understanding Python's "with" statement
- documen.all('')的使用方法
- python中'@'符号用作函数修饰符
- suse 11下编译使用boost-python报错:error: changes meaning of 'keywords' from 'struct boost::python::detail::keywords'
- Python(私有变量)类中的特殊方法
- python中的新型类及其实例详解