Let's talk about the module structure in this section.
The structure of the module is very traditional Chinese medicine, it can let maintenance personnel at a glance understand the code distribution, understand part of the code meaning
1. Documentation
Python specifically left a __doc__ dynamic variable to allow the outside world to read the object's document string
2. Structure
Let's give an example to illustrate:
#/usr/bin/env python start line ' This is a test module ' #模块文档 (document string) import sys# Reference module import osdebug=true# global variable class Fooclass (object ): #类定义 ' Foo class ' passdef Test (): #函数定义 ' test function ' foo=fooclass () if debug: print (" Welcome ") If __name__== ' __main__ ': #主程序 Test ()
1) Starting line, if it is in a Unix-like system, he does not have to start the interpretation right, directly can run the program
2) Module document or document string, mainly describes the role of modules, classes, functions, etc.
3) Reference module, mainly referring to the code reuse of other modules, the module is only introduced once, the module inside the function will not be imported
4) Global variables, classes, methods shared variables, generally we do not recommend the use of global variables, maintenance is more difficult, and consumption of memory
5) class definition
6) Function definition
7) The main program, whether the module is imported or directly when the script runs, he will execute. For the main program, it is generally a good place to put the test code, because before the import can test whether the method or as originally set.
In general, functional code is encapsulated in a class or method.
There are indentation problems, because the indentation in Python is extremely important for the interpreter, so in order to reduce indentation, it is recommended that multiple classes and functions be reused as much as possible.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
0 Basic python-3.4 module structure