[英]guidelines for importing modules in python
我知道有很多关于在python中导入模块的问题,但是我的问题似乎有些不同。
我试图了解何时必须导入整个模块,而不是何时必须导入模块中的特定条目。 似乎只有两种方式之一起作用。
例如,如果我想使用基名,则导入os.path并不能解决问题。
>>> import os.path
>>> basename('scripts/cy.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'basename' is not defined
相反,我需要从os.path中导入basename,如
>>> from os.path import basename
>>> basename('scripts/cy.py')
'cy.py'
换一种方式,如果我想使用shutil.copyfile,从shutil导入copyfile不起作用
>>>
>>> from shutil import copyfile
>>>
>>> shutil.copyfile('emma','newemma')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'shutil' is not defined
相反,我必须像
>>>
>>> import shutil
>>>
>>> shutil.copyfile('emma','newemma')
'newemma'
>>>
我能够做到这一点的唯一方法是通过实验。 有避免实验的指南吗?
如果导入
import os.path
那么你必须使用完整的命名空间os.path
os.path.basename()
如果from
导入
from shutil import copyfile
那么你就必须使用完整的命名空间shutil
copyfile(...)
就这样。
如果您as
import os.path as xxx
那么您必须使用xxx
而不是os.path
xxx.basename()
如果您使用from
和as
from os.path import basename as xxx
那么您必须使用xxx
而不是basename
xxx()
您可以使用表单模块导入*
from time import *
sleep(2)
它允许您调用其子模块,而不是:
from time import sleep
sleep(2)
要么:
import time
time.sleep(2)
这会导入包https://docs.python.org/2/tutorial/modules.html#importing-from-a-package的每个子模块
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.