Introduction to Python programming of 4 modules and packages
- 2020-04-02 13:46:44
- OfStack
The Python language is very powerful, and in addition to classes, there is also the concept of modules and packages, which is a bit like perl.
A module in Python
A module -- that's what we call a lib, but it can contain not just a bunch of functions, but it can also contain classes, and there's no way in python to include a file directly, like in C, and that's what packages are.
Python introduces modules in two ways:
1. Import module name (which actually corresponds to the filename.py)
2, Module name = s/s (" module file name (with no extension)")
You can also "import module name The as Alias "is used like this
Such as:
test.py
# -*- coding: gb18030 -*-
# The introduction of the module
import test_mod
# Call the function in the module
test_mod.my_func()
# Call the class in the module
tc = test_mod.test_cls()
tc.test_func()
test_mod.py Source as follows:
# -*- coding: gb18030 -*-
def my_func():
print 'I am a function in the module! '
class test_cls:
def test_func(self):
print 'I am a mothod in the class! '
Call the function or class in the module must be in the "module name. Class name | function name" way.
Just because of this, many in the python OS. Xx, sys. Xx, such as grammar, but it is not necessarily the object (between the object and the object appears very confusion, or you can think module is an object, but a special), it is a serious defect in the python language, but when you get used to these, it is easier to read the scripts for the python.
Sys and OS are the most commonly used modules in python
You need to know them.
Packages in Python
A package is essentially a package of modules to prevent collisions between module names. For a standard python program, the usual structure is:
app.py
appname
__init__.py
son_pack1
__init__.py
son_mod_1_1.py
son_mod_1_2.py
son_pack2
__init__.py
son_mod_2_1.py
son_mod_2_2.py
son_mod_1.py
.......
If you've learned Java, it's obvious that this is a way to find files by directory, but the difference is that each directory must take with s/s.py or it will not be recognized as a subdirectory of the package.
With three special variables, namely, s/s, s/s, s/s, s/s, s/s, s/s.
The method to call a class or function in the package is:
Package name. Subpackage name. Class name | function name
This is actually equivalent to a namespace in C++ or C#.
When you invoke a package, you need to register the directory and the method of invocation for the specific module
For example, to call son_mod_1_1.py
So:
appname.son_pack1.son_mod_1_1
Another way is to use Form keyword, method:
from appname.son_pack1 import son_mod_1_1
If you want to introduce all the modules in appname.son_pack1, then:
from appname.son_pack1 import *
For use of import *, please specify with s/s in s/y, e.g.
__all__ = ["son_mod_1_1", "son_mod_1_2"]