问题描述
在我尝试这个之前,我认为两者都是平等的:
I use to think both are equal until I tried this:
$python
Python 2.7.13 (default, Dec 17 2016, 23:03:43)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> root=Tk()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Tk' is not defined
>>> from Tkinter import *
>>> root=Tk()
那么这两种导入之间的核心差异是什么呢?模块?
So what's the core difference between these 2 kinds of import that import everything from a module?
谢谢。
推荐答案
导入x时,它将名称x绑定到x对象,它不会让您直接访问作为模块的任何对象,如果要访问任何需要指定的对象,请
when you import x , it binds the name x to x object , It doesn't give you the direct access to any object that is your module, If you want access any object you need to specify like this
x.myfunction()
另一方面你使用x import *导入它,它将所有功能带入你的模块,所以你可以直接访问它而不是x.myfunction()
On the other side when you import using from x import * , It brings all the functionalities into your module, so instead of x.myfunction() you can access it directly
myfunction()
例如假设我们有模块 example.py
def myfunction ():
print "foo"
现在我们有了主脚本 main.py ,它们使用了这个模块。
Now we have the main script main.py , which make use of this module .
如果你好你使用简单的导入然后你需要像这样调用myfunction()
if you use simple import then you need to call myfunction() like this
import example
example.myfucntion()
如果你使用from,你不需要使用模块名来引用函数,你可以像这样直接打电话
if you use from, you dont need to use module name to refer function , you can call directly like this
from example import myfunction
myfunction()
这篇关于Python:“import X”和“import X”之间的区别是什么?和“来自X import *”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!