This paper examines mainly the Python module file structure as follows.
Python file structure
Structure of the document (full example)
#/usr/bin/env python "this is a test module" import sys import os debug = True class FooClass (object): "Foo class" pass def test(): "test function" foo = FooClass() if debugL print 'ran test()' if __name__ == '__main__' test()
Documentation structure (branch presentations)
(1) Starting line (specify the version of Python used)
#/usr/bin/env python
(2) Module documentation (document string, if across the line with three single quotes to expand up)
"this is a test module"
(3) Module importing
import sys import os
(4) (Global) Variable Definitions
debug = True
(5) Class definition (if any)
class FooClass (object): "Foo class" pass (6)function definition(if not) def test(): "test function" foo = FooClass() if debugL print 'ran test()'
7) Main program
if __name__ == '__main__' test()
clarification
main program
- This part of the code is executed whether the current module is imported by the backing module or run directly as a script
Note: All modules have the ability to execute code.
- The highest-level Python statements (the ones without indentation) are executed when the module is imported, whether or not they actually need to be executed
- The proper way to do it: all functional code is built through functions except for those that really need to be executed, therefore:
Write large amounts of top-level executable code only in the main program module
The module used to be imported should only have a small amount of top-level executable code.
__name__ indicates how the module should be loaded (this allows for self-testing of the module).
- If the module is imported, the value of __name__ is the name of the module.
- If the module is directly executed, the value of __name__ is __main__.
summarize
Above is this article on Python module file structure code to explain all the content, I hope to help you. Interested friends can continue to refer to other related topics on this site, if there are inadequacies, welcome to leave a message to point out. Thank you for the support of friends on this site!