简体   繁体   中英

`from x import y` vs. `from x.y import *`

What is the difference between these two lines?

from PyQt4 import QtGui
from PyQt4.QtGui import *

The first line is "import QtGui class from module PyQt4".
But what does second line means? "Import everything from QtGui of module PyQt4".
Is not it the same?

First statement imports the specified module into the current namespace.
Second statement imports everything from the specified module into the current namespace.

So 1) means you still need to explicitly reference any classes/functions etc through the module namespace
2) Means you don't

Here's a compare and contrast that shows the difference

1)

import math

d = math.sqrt(10)

2)

from math import *

d = sqrt(10)

Note that you can choose to import a specific symbol from a module if you want ie

from math import sqrt
d = sqrt(10)

Packages may export more than one thing. The difference is that the first line imports a single object from the package, the second imports everything. If the package you are importing only exports one thing, the two are synonymous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM