Python--modules and packages

Python modules and packages

1. What is a module:

The Python standard library contains a large number of modules (called standard modules), as well as a large number of third-party modules, and developers themselves can develop custom modules. These powerful modules can greatly improve the development efficiency of developers.

Modules are Python programs.

A module can be compared to a box of building blocks through which toys of various themes can be spelled out. This is different from the functions described above. A function is only equivalent to a block, but a module (.py file) can contain multiple functions. That's a lot of blocks.

  • As the program functions become more complex, the program size will continue to increase. For ease of maintenance, it is usually divided into multiple files (modules), which can not only improve the maintainability of the code, but also improve the reusability of the code.

The reusability of the code is reflected in the fact that when a module is written, as long as a certain function in the module (implemented by variables, functions, and classes) is needed during the programming process, there is no need to do repetitive writing work, and it can be directly written in the program Import this module in to use this function.

A lot of packages have been talked about before:

  • Many containers, such as lists, tuples, strings, dictionaries, etc., are encapsulation of data;
  • A function is a wrapper around Python code;
  • A class is the encapsulation of methods and properties, it can also be said that it is the encapsulation of functions and data.
  • A module is also a kind of encapsulation, which writes the code that can realize a certain function in the same .py file.

2. Module import:

Use Python's existing standard library or third-party libraries provided by others.

Two ways to import:

  • import module-name1 [as alias1], module-name2 [as alias2], ...

  • from module-name import member-name1 [as alias1], member-name2 [as alias2], ...

# 导入sys整个模块
import sys
# 使用sys模块名作为前缀来访问模块中的成员
print(sys.argv[0])

# argv[0] 用于获取当前 Python 程序的存储路径

Alias ​​the module:

import sys as s
# 使用s模块别名作为前缀来访问模块中的成员
print(s.argv[0])

To import multiple modules at once:

import sys,os
# 使用模块名作为前缀来访问模块中的成员
print(sys.argv[0])
# os模块的sep变量代表平台上的路径分隔符
print(os.sep)

Import multiple modules and specify aliases separately:

# 导入sys、os两个模块,并为sys指定别名s,为os指定别名o
import sys as s,os as o

The following method is to specify the member name in the module:

from module name import member name as alias:

from sys import argv
# 使用导入成员的语法,直接使用成员名访问
print(argv[0])

To assign an alias to a member:

# 导入sys模块的argv成员,并为其指定别名v
from sys import argv as v
# 使用导入成员(并指定别名)的语法,直接使用成员的别名访问
print(v[0])

To import multiple members at once:

# 导入sys模块的argv,winver成员
from sys import argv, winver
# 使用导入成员的语法,直接使用成员名访问
print(argv[0])
print(winver)

3. Custom modules:

name = "Python教程"
add = "http://c.biancheng.net/python"
print(name,add)
def say():
    print("人生苦短,我学Python!")
class CLanguage:
    def __init__(self,name,add):
        self.name = name
        self.add = add
    def say(self):
        print(self.name,self.add)

if __name__ == '__main__':
    say()
    clangs = CLanguage("C语言中文网","http://c.biancheng.net")
    clangs.say()

Execute under the test02.py file, you can get:

Python教程 http://c.biancheng.net/python
人生苦短,我学Python!
C语言中文网 http://c.biancheng.net

Execute under test01.py:

Python教程 http://c.biancheng.net/python

The test function is only executed when the module file is directly run, and a judgment can be added when calling the test function, that is, the test function is called only when name ==' main '.

4. __all__ usage:

When we import a module into a file, we import variables, functions and classes whose names do not start with an underscore (single underscore "_" or double underscore "__"). Therefore, if we don't want a member in the module file to be imported and used in other files, we can add an underscore before its name.

Take the demo.py module file and test.py file created in the previous chapters as an example (they are located in the same directory), the content of each is as follows:

#demo.py
def say():
    print("人生苦短,我学Python!")
def hello():
    print("hello:china")
def show():
    print("Python教程:http://c.biancheng.net/python")
    
    
#test.py
from demo import *
say()
hello()
show()

Execute the test.py file:

人生苦短,我学Python!
C语言中文网:http://c.biancheng.net
Python教程:http://c.biancheng.net/python

If the show() function in the demo.py module does not want to be imported by other files, just change its name to _show() or __show().

By setting the all variable in the module file , when other files import the module in the form of "from module name import *", only the members specified in the all list can be used in this file.

Only the modules imported in the form of "from module name import *", when the module has an all variable, can only import the members specified by the variable, and the unspecified members cannot be imported.

def say():
    print("人生苦短,我学Python!")
def CLanguage():
    print("C语言中文网:http://c.biancheng.net")
def disPython():
    print("Python教程:http://c.biancheng.net/python")
__all__ = ["say","CLanguage"]

In the above code, only say() and CLanguage() can be displayed.

Once again, the all variable is limited to being introduced in other files in the form of "from module name import *". In other words, if the module is imported in the following two ways, the setting of the all variable is invalid.

5. Python package:

A package is a folder, but a file called " init.py " must exist under the folder .

An init.py module must be created under each package directory , which can be an empty module, and some initialization code can be written, its function is to tell Python to treat the directory as a package.

Note that init.py is different from other module files, the module name of this module is not init , but the package name it is in. For example, the module name of the init.py file in the settings package is settings.

Python library: Compared with modules and packages, library is a larger concept. For example, each library in the Python standard library has several packages, and each package has several modules.

Import of python package:

  • import package name[.module name[as alias]]
  • from package name import module name [as alias]
  • from package name. module name import member name [as alias]

6. View the document:

1. View module members:

dir() function:

import string
print(dir(string))

all variables:

import string
print(string.__all__)

2. View documentation and help information:

  • Use the help() function to get help information for a specified member (or even the module).
import my_package
help(my_package.module1)
  • Use the doc variable to get its documentation:
import my_package
print(my_package.module1.display.__doc__)

In fact, the bottom layer of the help() function is also implemented with the help of the doc attribute.

3. View the source file path of the module:

Find the specific storage location of the module (or package) file through the file attribute, and directly view its source code.

import my_package
print(my_package.__file__)

Note that not all modules provide the file attribute, because not all modules are implemented in Python language, and some modules use other programming languages ​​(such as C language).

Guess you like

Origin blog.csdn.net/weixin_53060366/article/details/130192448