预计阅读本页时间:-
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
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
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()