您的位置:首页 > 编程语言 > Python开发

Python 模块 & 作用域

2016-07-10 21:39 267 查看

1 模块

在这部分,主要区分模块、包、多层目录。
请注意,每一个包目录下面都会有一个__init__.py的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。__init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块,而它的模块名就是mycompany。
文件结构:
mycompany --包
__init__.py
abc.py --模块
xyz.py

1.1 使用模块

1.1.1 模块编写

[root@daidai python]# vi !$
vi hello_module.py
#!/usr/bin/python
# -*- coding:utf-8 -*-

'a hello test module' #任何模块代码的第一个字符串都被视为模块的文档注释
__author__ = 'daidai' #作者

import sys #导入模块
def test():
args = sys.argv #sys.argv接收命令的参数,采用list方式
if len(args) == 1:
print('Hello, world')
elif len(args) == 2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments')

if __name__ == '__main__':
test()
~
~
~
~
~
~
"hello_module.py" 18L, 331Cwritten
[root@daidai python]# pythonhello_module.py –实际上就是最后两行代码,执行了test函数
Hello, world
[root@daidai python]# pythonhello_module.py daidai
Hello, daidai!
Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。
[root@daidai python]# vi hello_module.py
#!/usr/bin/python
# -*- coding:utf-8 -*-

'a hello test module'
__author__ = 'daidai'

import sys
def test():
args = sys.argv
if len(args) == 1:
print('Hello, world')
elif len(args) == 2:
print('Hello, %s!' % args[1])
else:
print('Too many arguments')

#if __name__ =='__main__':
# test()
~
~
~
~
~
~
"hello_module.py" 18L, 333Cwritten
[root@daidai python]# pythonhello_module.py --并没有输出
[root@daidai python]# pythonhello_module.py daidai
[root@daidai python]# python
Python 3.5.0b4 (default, Jul 1 2016, 21:28:36)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] onlinux
Type "help","copyright", "credits" or "license" for moreinformation.
>>> import hello_module
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined
>>> hello_module.test() --调用模块中的函数
Hello, world
>>> hello_module.__author
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'hello_module' hasno attribute '__author'
>>> hello_module.__author__
'daidai'
>>> hello_module.__doc__
'a hello test module'

1.1.2 作用域

正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等;
类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名;
类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等;
def _private_1(name):
return 'Hello, %s' % name
def _private_2(name):
return 'Hi, %s' % name
def greeting(name):
if len(name) > 3:
return _private_1(name) --实现代码的封装和抽象
else:
return _private_2(name)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  模块 Python 作用域