模块相当于一个可以被多次使用的.py文件
不管你执行了多少次import,一个模块只会被导入一次
from 模块 import 模块中的指定部分
会将模块中的指定部分导入,而不会导入整个模块
from模块 import *
会导入模块中的所有项目,但不该被过多地使用
每个模块有各自独立的符号表,所以,模块的作者可以放心大胆的在模块内部使用这些全局变量,而不用担心把其他用户的全局变量搞混
__name__属性
当模块自身在运行时(执行模块内自己的函数时),__name__ == '__main__',当模块是被引入时(该模块执行另一个模块内的函数时),__name__ == '被调用模块的名字'
作用:不想让模块内自己的函数被别的模块使用。需要使用一个if语句
if __name__ == '__main__':
print('程序自身在运行')
else:
print('我来自另一模块')
只有自己才能使用print('程序自身在运行'),别的模块只能使用print('我来自另一模块')
dir()函数
dir()函数可以找到模块内定义的所有名称,以一个字符串列表的形式返回
import sys
print(dir(sys))
['__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']
包
sound/ 顶层包
__init__.py 初始化 sound 包,目录只有包含一个叫做 __init__.py 的文件才会被认作是一个包
formats/ 文件格式转换子包
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ 声音效果子包
__init__.py
echo.py
surround.py
reverse.py
...
filters/ filters 子包
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
导入方法
①import sound.effects.echo
使用时必须使用全名: sound.effects.echo.echofilter( )
如果使用形如 import item.subitem.subsubitem 这种导入形式,除了最后一项,都必须是包,而最后一项则可以是模块或者是包,但是不可以是类,函数或者变量的名字
②from sound.effects import echo
使用时不需要冗长的前缀:echo.echofilter( )
③from sound.effects.echo import echofilter
使用时可以直接使用函数:echofilter( )
当使用 from package import item 这种形式的时候,对应的 item 既可以是包里面的子模块(子包),也可以是包里面定义的其他名称,比如函数,类或者变量