jonvi 发表于 2017-4-22 12:36:46

python 的模块管理

同一目录/test下
函数模块文件
fun.py

#coding=utf-8
def hello():
print('hello');

主模块文件
hello.py
#! python
#coding=utf-8
import sys
import fun
sys.stdout.write("hello from Python %s\n" % (sys.version,))
fun.hello();

调用时,需要模块前缀fun+函数名,如fun.hello()
或者

#! python
#coding=utf-8
import sys
#通过函数名hello导入自定义模块
from fun import hello
#导入自定义模块里所有函数到当前文件
#from fun import *
sys.stdout.write("hello from Python %s\n" % (sys.version,))
hello();

使用from import导入,只需写函数名hello()。
内置的dir()函数,可以列出当前定义的名称列表,
dir(modulename),列出导放的该module定义的名称列表。

E:\python>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import fun
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'fun']
>>> dir(fun)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'hello', 's']
>>>
页: [1]
查看完整版本: python 的模块管理