`
zsjg13
  • 浏览: 149982 次
  • 性别: Icon_minigender_1
  • 来自: 安徽
社区版块
存档分类
最新评论

Grouping Code with Modules

 
阅读更多

    一个模块就是一个文件,它里面就是Python代码。一个模块中可以定义函数、类以及变量。一个模块还可以包含 runnable code。

    将相关的代码放到一个模块中使得代码更容易理解和使用。当编写一个程序时,不管何时该文件开始变得太大或执行太多不同功能时就要将代码分割进模块中。

 

1、Laying out a module

    模块中元素的通常顺序是:

✦ Docstring and/or general comments (revision log or copyright information,

and so on)

✦ Import statements (see below for more information on importing modules)

✦ Definitions of module-level variables (“constants”)

✦ Definitions of classes and functions

✦ Main function, if any

    不要求一定这么做,但它工作得很好并被广泛采用。

注意:人们常常将频繁用到的值放到都是大写字母变量中以便于维护,或者只是更易于阅读。例如:

FTP_PORT = 21 # The standard FTP server control port

    这样的一个变量就是“约定中的常量”——Python不会禁止修改它,但调用者不应当修改它的值。

 

2、Taking inventory of a module

    函数 dir(module) 定义在module中的变量、函数,以及类的一个列表。如果不带参数,dir 返回所有当前定义的名字的一个列表。dir(__builtin__) 返回所有built-in names 的一个列表。例如:

>>> dir() # Just after starting Python

[‘__builtins__’, ‘__doc__’, ‘__name__’]

>>> import sys

>>> dir()

[‘__builtins__’, ‘__doc__’, ‘__name__’, ‘sys’]

    你可以向 dir 传任何对象(或类),此时得到的是类成员列表。

分享到:
评论

相关推荐

    Foundations for Analytics with Python O-Reilly-2016-Clinton W. Brownley

    These two techniques—grouping or binning data with a dictionary and keeping track of the current row and the previous row—are very powerful capabilities that enable you to handle many common ...

    Find Reference 2 2.4.3.unitypackage

    查看资源引用情况的工具。版本2.4.3。 Optimize final build size and keep your project clean Beginner's Guide | Scene Reference's Guide ...- Works with Unity 5.x, 2017.x, 2018.x, 2019.x

    FlexGraphics_V_1.79_D4-XE10.2_Downloadly.ir

    - FIX: Support for the Import/Export modules that can't work with Streams. Added TFlexFileFormat.StreamSupport property (default True), which difines, is it necessary to open file stream or give the ...

    ZendFramework中文文档

    Routing to modules 7.11.4. 模块或全局缺省控制器 7.12. MVC 异常 7.12.1. 介绍 7.12.2. 如何处理异常? 7.12.3. 可能遭遇的MVC异常 7.13. 从以前的版本移植 7.13.1. 从 1.0.x 到 1.5.0 或更新的版本的移植 ...

    SystemVerilog for Design(2nd edition)

    2.2.3 Source code order.............................................................................................17 2.2.4 Coding guidelines for importing packages into $unit ..........................

Global site tag (gtag.js) - Google Analytics