`
syzxlyx_cu
  • 浏览: 18257 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Module Imports and Reloads

 
阅读更多
在python中,每个文件名以。py结尾的源代码文件叫module。其他文件能import的形式导入来使用其中的东西。python是以基于模块为服务模型的核心思想,其中一个设置为main或top-level文件,由他发起整个应用程序。
import file动作默认情况下一个session一次,也就是说默认一个模块一个session导入一次,impport 第二次时什么也不做。这是因为impport所耗资源比较大,假如确实要重新导入,则要使用imp保准库模块进行reload。
>>> from imp import reload # Must load from module in 3.0
>>> reload(script1)

reload模块名要用括号,import不需要。因为reload是功能调用,import是一条语句。
Version skew note: Python 3.0 moved the reload built-in function to the
imp standard library module. It still reloads files as before, but you must
import it in order to use it. In 3.0, run an import imp and use
imp.reload(M), or run a from imp import reload and use reload(M), as
shown here. We’ll discuss import and from statements in the next section,
and more formally later in this book.
If you are working in Python 2.6 (or 2.X in general), reload is available
as a built-in function, so no import is required. In Python 2.6, reload is
available in both forms—built-in and module function—to aid the transition
to 3.0. In other words, reloading is still available in 3.0, but an
extra line of code is required to fetch the reload call.
The move in 3.0 was likely motivated in part by some well-known issues
involving reload and from statements that we’ll encounter in the next
section. In short, names loaded with a from are not directly updated by
a reload, but names accessed with an import statement are. If your
names don’t seem to change after a reload, try using import and
module.attribute name references instead.
By contrast, the basic import statement runs the file only once per process, and it makes the file a separate module namespace so that its assignments will not change variables in your scope. The price you pay for the namespace partitioning of modules is the need to reload after changes.
Version skew note: Python 2.6 also includes an execfile('module.py')
built-in function, in addition to allowing the form exec(open('module.py')), which both automatically read the file’s content. Both of these are equivalent to the
exec(open('module.py').read()) form, which is more complex but
runs in both 2.6 and 3.0.
Unfortunately, neither of these two simpler 2.6 forms is available in 3.0,
which means you must understand both files and their read methods to
fully understand this technique today (alas, this seems to be a case of
aesthetics trouncing practicality in 3.0). In fact, the exec form in 3.0
involves so much typing that the best advice may simply be not to do
it—it’s usually best to launch files by typing system shell command lines
or by using the IDLE menu options described in the next section
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics