hug2wisdom / learnpython

note the points of learn python
0 stars 0 forks source link

Module #10

Open hug2wisdom opened 5 years ago

hug2wisdom commented 5 years ago

Within a module, the module’s name (as a string) is available as the value of the global variable __name__. module.__name__ 表示模块的名字


python fibo.py <arguments> 想要把模块当作脚本使用,则需要在模块内部最后添加

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

这里只是举例。if __name__ == "__main__ 是必须的,you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file。

主要运用场景:This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).


dir() Note that it lists all types of names: variables, modules, functions, etc.

hug2wisdom commented 5 years ago

Packages

eg:

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

Note Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item. 最后一个元素不可以是类,函数或者变量。

if the package's init.py 里面有 all('item1', 'item2', 'item3'),则可以使用:from sound.effects import * ,不然一般不建议使用。

hug2wisdom commented 5 years ago

每个模块都有一个name属性,当其值是'main'时,表明该模块自身在运行,否则是被引入。

说明:namemain 底下是双下划线, 是这样去掉中间的那个空格。