Differences between revisions 3 and 4
Revision 3 as of 2005-06-09 06:21:47
Size: 3051
Editor: ZoomQuiet
Comment:
Revision 4 as of 2009-12-25 07:17:59
Size: 3048
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
[wiki:PyCNmail/2005-June/011187.html 学习PYTHON 入门日志 (七)] [[PyCNmail:2005-June/011187.html|学习PYTHON 入门日志 (七)]]
Line 5: Line 5:
[[TableOfContents]] <<TableOfContents>>

学习PYTHON 入门日志 (七)

050609 模块和包

{{{继续:模块和包 28:模块

  • 模块就是一些函数和一些class的一个集合,放到一个*.py 例如 sys 就是一个模块 import就是加载一个模块,dir显示出模块里面的 变量成员

    >>> import sys >>> dir(sys) ['doc', 'name', 'stderr', 'stdin', 'stdout', 'argv', 'builtin_module_names', 'copyright', 'dllhandle', 'exc_info',

'exc_type',

  • 'exec_prefix', 'executable', 'exit', 'getrefcount',

'hexversion', 'maxint',

  • 'modules', 'path', 'platform', 'prefix', 'ps1', 'ps2',

'setcheckinterval',

  • 'setprofile', 'settrace', 'stderr', 'stdin', 'stdout',

'version', 'winver']

  • 我会写

    文件 model_test.py ,但不知道 if name=="main": 是什么意思

    • """ this is a module """ one = "a attribute" def fun():
      • return "haha"

      if name=="main":

      • fun()

      >>> import model_test >>> fun <function fun at 0x00992E30> >>> fun() 'haha' >>> >>> fun <function fun at 0x00992E70> >>> fun() 'haha' >>> one 'a attribute' >>> print doc this is a module

      >>> 模块也是个对象可以赋值的,如

      >>> pp=model_test >>> pp.fun <function fun at 0x00992EF0> >>> pp.fun() 'haha' 要仔细体会Python 中 很多对象的概念 模块的使用要注意name space的概念 注意自己模块的名字不要和系统的名字一样

29:包

  • 包packge 是一组module 的集合。
    • 建立一个包的过程是这样的 1:建立一个目录如 testpackage

      2:建立一个空文件 int.py (我不知道这个文件是做什么用的) 3:把要打包的*.py文件复制到该目录下 按照如下的方式访问就可以了

      >>> import testpackage.testmodule >>> testpackage.testmodule.sayHello() Hello 包是一种防止名字冲突,我更喜欢叫,名字空间的污染 同时包里面还可以打包 用来更方便的管理模块。

以上是Python 模块和包 下一篇将是Python 的name space

邹胖小 2005年6月8日 祝大家快乐安康 今天高考结束了 }}}

__name__ 技巧

{{{这是一个运行的技巧。当此模块为主程序时,name的值为main,当模块被导入时,它的值是模块名。因此它可以用来对一些模块作测试,这样可以单独运行这些模块,则 if name == 'main':就会执行。如果是被其它模块导入,则它不会执行。 }}}

  • 即可以通过这种方式在 文件中进行自测部分的开发;

ChaoZouPyNotes/2005-06-09 (last edited 2009-12-25 07:17:59 by localhost)