python中的关键字import

来源:互联网 发布:ubuntu查看cpu详情 编辑:程序博客网 时间:2024/05/18 06:21

  先看文件结构

[mytest]$ tree
.
|-- a.py
|-- b.py
`-- newtest
    |-- c.py
    `-- d.py

[mytest]$ cat a.py
def fun1():
    print 'fun1 in a.py'


如果想在b.py中调用a.py中的函数func1(),可以这么做

[mytest]$ cat b.py 
import a
a.fun1()

如果不想每次调用函数时都加上调用模块的名字(如本例中的'a'),可以这么做

[mytest]$ cat b.py 
from a import fun1
fun1()

如果我们想再b.py中调用文件夹‘newtest’下得文件'c.py',如果向下面这么写,导入不会成功

[mytest]$ cat b.py
import newtest.c
[mytest]$ python b.py 
Traceback (most recent call last):
  File "b.py", line 1, in ?
    import newtest.c
ImportError: No module named newtest.c

错误的原因是python要求每个文件夹下必须有__init__.py文件(即使里面为空),才能被当做一个package处理。这样我们在newtest文件夹下面增加一个文件名为__init__.py的空文件就可以了。另外,我们可以在__init__.py文件中对变量__all__进行赋值,在这个(__all__)list里面的文件才能被外部调用。

0 0