Python模块学习
6. Modules
If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.
如果你关闭Python解释器(IDLE),然后再打开,那么以前变量的定义则会丢失。因此,如果你想要写长一点的程序,最好先在编辑器中编写Python程序,然后将文件作为输入导入到IDLE解释执行。这就是所谓的创建一个脚本。当你的程序变得越来越大,你可能想要将程序分开到几个文件中。你可能想要写一个便利的函数,能够在几个程序中重复利用。
To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).
为了支持这种功能,Python可以把代码用文件存储,并作为一个脚本,或用来与解释器交互。这种文件就叫做模块。模块中定义可以被导出到另一个模块中或导入到main模块中。
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:
一个模块就是一个文件,这个模块包含了Python的定义和语句。文件的名字就是模块的名字加后缀.py。在模块内部,该模块的名字可以使用全局变量__name来表示。例如,使用你最喜欢的文本编辑器创建一个文件fibo.py,文件内容如下:
# Fibonacci numbers module def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print() def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following command:
打开Python IDLE,用下面的命令导入模块(一般Python是通过sys.path指定的路径搜索模块):
>>> import fibo
This does not enter the names of the functions defined in fibo directly in the current symbol table; it only enters the module namefibo there. Using the module name you can access the functions:
这个导入命令,不会将该模块的所有函数的名字自己导入到当前的符号表中,它仅仅只是将模块的名字导入到当前的符号表中,使用模块的名字,你可以访问它的函数:
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
If you intend to use a function often you can assign it to a local name:
你也可以将函数赋给本地变量:
>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
6.1. More on Modules
A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. [1] (They are also run if the file is executed as a script.)
模块包含可执行语句和函数定义。这些语句用于初始化模块,他们仅仅在模块第一次导入时被执行。
Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.
每一个模块有它自己的符号表,这个符号表可以当作是存储模块中所有函数定义的全局符号表。因此,模块的拥有者可以在模块中使用全局变量而不用担心和另一个用户的全局变量引发冲突。另一方面,如果你很清楚你的意图,你可以访问模块的函数,请使用modname.itemname
Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names are placed in the importing module’s global symbol table.
模块能够导入其他模块。一种约定俗成的做法是:将所有import语句放在模块的开头。被导入的模块名字会被放置在当前模块的全局符号表中。
There is a variant of the import statement that imports names from a module directly into the importing module’s symbol table. For example:
这里列举了几种不同形式的import语句,从一个模块中直接导入函数到当前模块的符号表中:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).
这种导入方式不会将模块名字fibo放入到当前模块的符号表中(例如,输入fibo是未定义的)。
There is even a variant to import all names that a module defines:
这是另一种导入形式:导入所有在模块中定义的名字:
>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This imports all names except those beginning with an underscore (_). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.
这种导入方式会将所有的名字导入到当前模块的符号表中,除开那些以下划线_开头的变量。在大部分情况下,Python程序员是不会使用这种导入方式的。因为这样会使你导入一些你未知的一些名字到解释器中,可能就会覆盖已经定义的变量。
Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.
注意,一般使用import * 是不被赞成的,因为它的可读性很差。然而,在解释器中为了节省输入,这种形式的导入也是OK的。仅此而已。
6.1.1. Executing modules as scripts
When you run a Python module with
当你这样运行Python模块:
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:
当你输入上面的语句时,fibo模块将会被执行,前提是__name__必须设为"__main__"。这就意味着你必须在fibo模块最后面加入下面的代码:
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:
你不但可以把它当脚本使用,还可以称为可导入的模块,因为分析命令行的代码仅仅当模块的文件名为main.py时才会被执行。
If the module is imported, the code is not run:
如果导入模块,代码不会运行:
>>> import fibo
>>>
6.1.2. The Module Search Path
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
当模块spam被导入后,解释器首先在内置的模块中寻找该模块的名字。如果没找到,就会在变量sys.path指定的路径中寻找文件名为spam.py的文件。sys.path初始化的路径包括:
- The directory containing the input script (or the current directory when no file is specified).
- 当前程序所在目录
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- PYTHONPATH(一个目录列表,这个变量就是系统环境变量)
- The installation-dependent default.
- Python默认安装目录。
After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.
当sys.path初始化后,Python程序可以修改sys.path的路径。当前正在运行的脚本所在的目录放置在搜索路径的最开头,也就是标准库模块路径的前面。这就意味着如果当前模块的名字和标准库模块的名字相同时,则会替换掉该标准库模块。如果你不是有意要替换该标准库模块,那么可能就会出现错误。
6.1.3. “Compiled” Python files
To speed up loading modules, Python caches the compiled version of each module in the __pycache__ directory under the namemodule.version.pyc, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as __pycache__/spam.cpython-33.pyc. This naming convention allows compiled modules from different releases and different versions of Python to coexist.
为了加速加载模块。Python缓存了已经编译好的每个模块的版本,并放置在__pycache__目录下。编译好的模块的名字为:module.version.pyc(module为对应的模块名,version为Python对应的版本)。例如:在CPython release 3.3版本上编译spam.py将会缓存__pycache__/spam.cpython-33.pyc。这种缓存的命名风格允许不同的Python版本共存。
Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.
针对编译的版本,Python检查源码的修改时间判断该版本是否过期或者需要重新编译。这完全是一个自动完成的过程。同样,编译的模块也是平台独立的,因此同样的库可以在不同架构的系统上运行。
Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.
Python在两种情况下不会检查缓存。第一,如果模块执行从命令行加载,则该模块会被重新编译,并且不会保存结果。第二,如果没有源码的模块,将不会检查缓存。为了支持只有编译版本的模块,必须将该模块放置在源码模块目录下,并且不能有该模块的源码。
Some tips for experts:
- You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have a .pyo rather than a .pyc suffix and are usually smaller. Future releases may change the effects of optimization.
- A program doesn’t run any faster when it is read from a .pyc or .pyo file than when it is read from a .py file; the only thing that’s faster about .pyc or .pyo files is the speed with which they are loaded.
- The module compileall can create .pyc files (or .pyo files when -O is used) for all modules in a directory.
- There is more detail on this process, including a flow chart of the decisions, in PEP 3147.
6.2. Standard Modules
Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg module is only provided on Windows systems. One particular module deserves some attention: sys, which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:
Python有一个标准模块库,该库的说明在另一个单独的文档中,叫做Python库参考。有些模块是解释器内置的(意味着不需要使用import语句);虽然这些内置的模块提供了操作权限(例如访问系统调用),但却不是语言核心的一部分。这些模块是可以通过配置来选择的,并且依赖于不同的平台。例如:winreg模块仅仅在Windows系统中使用。另一个特殊的模块sys值得引起注意,它内置于每一个Python解释器中。变量sys.ps1和sys.ps2定义了两个提示符字符串:
>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>
These two variables are only defined if the interpreter is in interactive mode.
这两个变量仅仅是在解释器在交互模式的环境中才被定义。
The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:
变量sys.path包含一个字符串的列表,它觉得了解释器寻找模块的搜索路径。环境变量PYTHONPATH的路径作为它初始化的一部分,如果没有设置PYTHONPATH环境变量,则使用默认的内置路径。你可以标准的列表操作来修改它:
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
6.3. The dir() Function
The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:
内置的函数dir()常被用来寻找那些已经被模块定义了的变量名字,它返回一个已经排序好了的字符串:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
'__package__', '__stderr__', '__stdin__', '__stdout__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
'_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook',
'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
'thread_info', 'version', 'version_info', 'warnoptions']
Without arguments, dir() lists the names you have defined currently:
如果不输入参数,dir()函数将会列出当前已经定义的名字:
>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']
Note that it lists all types of names: variables, modules, functions, etc.
注意:它会列出所有的名字:变量,模块,函数等等。
dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard modulebuiltins:
dir()不会雷锤内置的函数名和变量名。如果你想要列出这些名字,他们被定义在标准模块builtins中:
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
'NotImplementedError', 'OSError', 'OverflowError',
'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
'__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
'zip']
6.4. Packages
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.Bdesignates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or the Python Imaging Library from having to worry about each other’s module names.
包是一种构建Python模块命名空间的方式,通过使用"packagename.modulename"。例如,模块名:A.B 说明子模块B在包A中。
Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem):
假设你希望设计一个模块的集合(也就是设计一个包)来统一处理音频文件和音频数据。这里有许多不同的音频格式(通常可以通过后缀来识别,例如.wav,.aiff,.au),因此你可能需要创建和维护增加的模块来处理不同的文件格式之间的转换。同样,你可能也想要在处理音频数据上执行多种操作,因此,你将会写一个无尽的流模块来处理这些操作。这里有一个包的设计架构可能是你需要的:
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
...
filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.
当你导入包的时候,Python将通过sys.path指定的路径来寻找包的子目录。
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
__init__.py文件是必须要存在的,这样Python才会将目录看作是包; 如果你使用一个普遍的名字命名包,例如string,如果后面有string模块,则会使该模块失效。最简单的情况是,__init__.py是一个空文件,但是它也可以包含包的初始化代码或者设置变量__all__的值,下面将会更详细的表述。
Users of the package can import individual modules from the package, for example:
包的使用者,可以从包中导入单个模块,例如:
import sound.effects.echo
This loads the submodule sound.effects.echo. It must be referenced with its full name.
加载子模块sound.effects.echo.调用时必须使用全名称:
sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
An alternative way of importing the submodule is:
另一种替代方式是:
from sound.effects import echo
This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:
这也是加载子模块echo,调用时不需要加包的前缀,因此可以这样使用:
echo.echofilter(input, output, delay=0.7, atten=4)
Yet another variation is to import the desired function or variable directly:
还有一种方式是直接导入想调用的函数:
from sound.effects.echo import echofilter
Again, this loads the submodule echo, but this makes its function echofilter() directly available:
同样,加载子模块echo,但是可以直接使用函数echofilter():
echofilter(input, output, delay=0.7, atten=4)
Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.
注意,当使用语句from package import item,这个item可以是子模块(或子包)也可以是包里面定义的对象,比如函数,类或者变量。import语句首先检查item是否在包中已经定义,如果没有,它就认为这是一个模块,并尝试加载它,如果加载失败,则抛出ImportError异常。
Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.
相反,当使用语句import item.subitem.subsubitem时,除开最后一个subsubitem,其他都必须是包;最后一个subsubitem可以是模块,也可以是包,但不能是类或者函数、变量。
6.4.1. Importing * From a Package
Now what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.
当用户使用from sound.effects import*时,则所有的模块都被导入,这将会花费很长的时间,并且可能产生意想不到的负面效果。
The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sound/effects/__init__.py could contain the following code:
唯一的解决办法就是包的作者提供一个显式的包的索引。import语句使用下面的惯例:如果一个包的__init__.py文件定义了变量__all__时,当使用语句from package import*,则会导入__all__变量所定义列表中的值。当有新版本的包要发布时,应该由作者保持对该列表的更新。当作者不想看到用户使用import *语句时,包的作者也可以决定不使用它。例如,文件sound/effects/__init__.py包含下面的代码:
__all__ = ["echo", "surround", "reverse"]
This would mean that from sound.effects import * would import the three named submodules of the sound package.
这就意味着from sound.effects import *将会导入effects包的三个子模块。
If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effectsinto the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous importstatements. Consider this code:
如果没有定义变量__all__,语句from sound.effects import*将不会把effect包的子模块导入到当前的命名空间中;它仅仅只确保包sound.effects被导入,然后再导入在effects包中定义的变量名。这包含任何在__init__.py文件中定义的变量名。考虑下面的代码:
import sound.effects.echo
import sound.effects.surround
from sound.effects import *
In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effectspackage when the from...import statement is executed. (This also works when __all__ is defined.)
在这个例子中,模块echo和surround被导入到当前的命名空间中,因为当from...import语句被执行时,他们就被定义在sound.effects包里面。
Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practise in production code.
尽管某些模块只是用来导出变量名,但import *始终被认为是一种不好的导入方式。
Remember, there is nothing wrong with using from Package import specific_submodule! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.
记住,使用from Package import specific_submodule是不会错的!实际上,这也是被建议的一种方式,
6.4.2. Intra-package References
When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effectspackage, it can use from sound.effects import echo.
当一个包有子包时(例如包sound),你可以使用绝对路径引用包同级的子模块。例如,如果模块sound.filters.vecoder需要使用sound.effects包中echo模块,可以使用语句:from sound.effects import echo。
You can also write relative imports, with the from module import name form of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:
你也能够用相对路径导入通过 rom module import name形式的导入语句。这些导入语句需要使用 . 来表示当前或父包。例如当在surround模块中使用下面的其他子模块时,你可以使用:
from . import echo
from .. import formats
from ..filters import equalizer
Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.
注意,相对路径的导入是基于当前模块的。因为main模块的名字总是"__main__",如果模块打算当作Python应用程序的主模块使用时,必须总是使用绝对路径。
6.4.3. Packages in Multiple Directories
Packages support one more special attribute, __path__. This is initialized to be a list containing the name of the directory holding the package’s __init__.py before the code in that file is executed. This variable can be modified; doing so affects future searches for modules and subpackages contained in the package.
包还支持其他特殊的属性,例如__path__。这个变量定义了一个列表,该列表包含了包的__init.__py所在的目录路径。这个变量能被修改。这将影响包中对子包和子模块的搜索。
While this feature is not often needed, it can be used to extend the set of modules found in a package.
然而这种特性不是常需要的,它能够用来扩展包中子模块的搜索路径。
转自:http://www.cnblogs.com/lijie-vs/p/4343350.html
Python模块学习的更多相关文章
- 【转】Python模块学习 - fnmatch & glob
[转]Python模块学习 - fnmatch & glob 介绍 fnmatch 和 glob 模块都是用来做字符串匹配文件名的标准库. fnmatch模块 大部分情况下使用字符串匹配查找特 ...
- 【目录】Python模块学习系列
目录:Python模块学习笔记 1.Python模块学习 - Paramiko - 主机管理 2.Python模块学习 - Fileinput - 读取文件 3.Python模块学习 - Confi ...
- Python模块学习filecmp文件比较
Python模块学习filecmp文件比较 filecmp模块用于比较文件及文件夹的内容,它是一个轻量级的工具,使用非常简单.python标准库还提供了difflib模块用于比较文件的内容.关于dif ...
- python模块学习第 0000 题
将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果. 类似于图中效果: 好可爱>%<! 题目来源:https://github.com/Yixiao ...
- Python模块学习:logging 日志记录
原文出处: DarkBull 许多应用程序中都会有日志模块,用于记录系统在运行过程中的一些关键信息,以便于对系统的运行状况进行跟踪.在.NET平台中,有非常著名的第三方开源日志组件log4net ...
- 解惑Python模块学习,该如何着手操作...
Python模块 晚上和朋友聊天,说到公司要求精兵计划,全员都要有编程能力.然后C.Java.Python-对于零基础入门的,当然是选择Python的人较多了.可朋友说他只是看了简单的语法,可pyth ...
- Python模块学习系列
python模块-time python模块-datetime python模块-OS模块详解
- Python模块学习遇到的问题
Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案 Python使用import导入模块 ...
- Python 模块学习:re模块
今天学习了Python中有关正则表达式的知识.关于正则表达式的语法,不作过多解释,网上有许多学习的资料.这里主要介绍Python中常用的正则表达式处理函数. 方法/属性 作用 match() 决定 R ...
随机推荐
- oracle调整表中列顺序
有一个哥们提出一个问题: 有个表,创建时候的列顺序是a,b,c 如何使用select * 的时候,让列的显示顺序是a,c,b 而且任性地必须使用select *来查询,且不能重建表. 假设有个表tes ...
- 【转】线程、Thread类和线程终止
一.线程Thread启动 0. Thread类实现了java.lang.Runnable接口,即实现了run方法.虽然在Sun JDK中,start()调用了start0()方法,start0()方法 ...
- iphone 语音备忘录 同步问题
iphone 是很人性化的,但itune是反人类的. 我想同步电话里的语音备忘录,结果有几个记录在itunes里面是不显示的,无法同步出来. 找了很多解决方法,最后找了ifunbox才搞定.
- Java I/O解读与使用实例
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 摘要:本文主要讲解了Java I/O解读与使用实例. 一.I/O基本概念 I/O全称是Inpu ...
- HTML语言的一些元素(一)
1)标题的六个等级:<h1>,<h2>,<h3>,<h4>,<h5>,<h6>.如果写了诸如:<h7>等,则作为正文 ...
- C++Primer 第十九章
//1.控制内存分配: //A:某些应用程序对内存分配有特殊的需求,因此我们无法将标准内存管理机制直接应用于这些程序.它们常常需要自定义内存分配的细节,比如使用关键字new将对象放置在特定的内存空间中 ...
- spfa的SLF优化
spfa的SLF优化就是small label first 优化,当加入一个新点v的时候如果此时的dis[v]比队首dis[q.front()]还要小的话,就把v点加入到队首,否则把他加入到队尾,因为 ...
- C#: 自定义控件
(一)复合控件 http://wenku.baidu.com/link?url=y4BdtX3mOer4Hdin019jJpXJLi-2_ehmEo7i08cxEp1OR_3gb5CqaHrnNEB2 ...
- 动态LOV语句、向具有LOV的ITEM赋值时报FRM-40212需要验证错误
网上解决方法: http://www.itpub.net/thread-845812-2-1.html http://blog.csdn.net/rfb0204421/article/details/ ...
- beta-1阶段各组员的贡献分分配
小组名称:nice! 小组成员:李权 于淼 刘芳芳 韩媛媛 宫丽君 项目内容:约跑app 分数分配规则 个人贡献分=基本贡献分*0.2+特殊贡献分*0.3+个人代码贡献量*0.5 其中 基本贡献分,特 ...