What is the difference between import modx and fro

2020-02-08 04:18发布

If I were to import some module called modx, how would that be different from saying

from modx import *

Wouldn't all the contents be imported from each either way? This is in python just to clarify.

3条回答
时光不老,我们不散
2楼-- · 2020-02-08 04:41

Common question with many faq's to answer... here is one: http://effbot.org/zone/import-confusion.htm

Essentially to answer your specific question the second form (from modx import *) you get only the public items in modx

查看更多
【Aperson】
3楼-- · 2020-02-08 04:42

If you import somemodule the contained globals will be available via somemodule.someglobal. If you from somemodule import * ALL its globals (or those listed in __all__ if it exists) will be made globals, i.e. you can access them using someglobal without the module name in front of it.

Using from module import * is discouraged as it clutters the global scope and if you import stuff from multiple modules you are likely to get conflicts and overwrite existing classes/functions.

查看更多
地球回转人心会变
4楼-- · 2020-02-08 04:44

If a defines a.b and a.c...

import a
a.b()
a.c()

vs.

from a import b
b()
c() # fails because c isn't imported

vs.

from a import *
b()
c()

Note that from foo import * is generally frowned upon since:

  1. It puts things into the global namespace without giving you fine control
  2. It can cause collisions, due to everything being in the global namespace
  3. It makes it unclear what is actually defined in the current file, since the list of what it defines can vary depending on what's imported.
查看更多
登录 后发表回答