Python: What's the difference between “import

2019-09-22 10:42发布

This question already has an answer here:

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?

Thanks.

1条回答
狗以群分
2楼-- · 2019-09-22 11:11

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()

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 ()

for example lets suppose we have module example.py

def myfunction ():
    print "foo"

Now we have the main script main.py , which make use of this module .

if you use simple import then you need to call myfunction() like this

import example

example.myfucntion()

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()
查看更多
登录 后发表回答