This question already has an answer here:
- Use 'import module' or 'from module import'? 16 answers
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.
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
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
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
if you use from, you dont need to use module name to refer function , you can call directly like this