第542页 | Learning Python | 阅读 ‧ 电子书库

同步阅读进度,多语言翻译,过滤屏幕蓝光,评论分享,更多完整功能,更好读书体验,试试 阅读 ‧ 电子书库

The as Extension for import and from

Both the import and from statements have been extended to allow an imported name to be given a different name in your script. The following import statement:

import modulename as name

is equivalent to:

import modulename
name = modulename
del modulename                                # Don't keep original name

After such an import, you can (and in fact must) use the name listed after the as to refer to the module. This works in a from statement, too, to assign a name imported from a file to a different name in your script:

from modulename import attrname as name

This extension is commonly used to provide short synonyms for longer names, and to avoid name clashes when you are already using a name in your script that would otherwise be overwritten by a normal import statement:

import reallylongmodulename as name           # Use shorter nickname
name.func()

from module1 import utility as util1          # Can have only 1 "utility"
from module2 import utility as util2
util1(); util2()

It also comes in handy for providing a short, simple name for an entire directory path when using the package import feature described in Chapter 23:

import dir1.dir2.mod as mod                   # Only list full path once
mod.func()

请支持我们,让我们可以支付服务器费用。
使用微信支付打赏


上一页 · 目录下一页


下载 · 书页 · 阅读 ‧ 电子书库