Difference between Module and Package in Python

Most of the content of this article is reprinted to: Liao Xuefeng's official website

 

1. Module

In the development process of computer programs, as more and more program codes are written, the code in a file will become longer and longer, and it will become more and more difficult to maintain.

In order to write maintainable code, we group many functions into different files, so that each file contains relatively little code. Many programming languages ​​use this way of organizing code. In Python, a .pyfile is called a module .

What are the benefits of using modules?

The biggest benefit is that the maintainability of the code is greatly improved. Second, writing code doesn't have to start from scratch. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python built-in modules and modules from third parties.

Using modules also avoids conflicting function names and variable names. Functions and variables with the same name can exist in different modules, so when we write our own modules, we don't have to consider that the names will conflict with other modules. But also pay attention to try not to conflict with built-in function names.

You might also think, what if different people write modules with the same name? In order to avoid module name conflicts, Python introduces a method of organizing modules by directory, called a package .

For example, a file is a module abc.pynamed , and a file is a module named .abcxyz.pyxyz

Now, suppose our abcand xyzthese two module names conflict with other modules, so we can organize modules by packages to avoid conflicts. The method is to choose a top-level package name, for example mycompany, store it in the following directory

mycompany
├─ __init__.py
├─ abc.py
└─ xyz.py

    After the package is introduced, as long as the top-level package name does not conflict with others, all modules will not conflict with others. Now, abc.pythe name of the module becomes mycompany.abc, similarly, xyz.pythe module name of mycompany.xyz.

Please note that there will be a file under each package directory __init__.py, this file must exist, otherwise, Python will treat this directory as a normal directory, not a package. __init__.pyIt can be an empty file, or it can have Python code, because __init__.pyit is a module, and its module name is mycompany.

Similarly, there can be multi-level directories to form a multi-level hierarchical package structure. For example, the following directory structure:

mycompany
 ├─ web
 │  ├─ __init__.py
 │  ├─ utils.py
 │  └─ www.py
 ├─ __init__.py
 ├─ abc.py
 └─ xyz.py

www.pyThe module name of the file ismycompany.web.www

Notes: When you create your own modules, you should pay attention to the naming, which cannot conflict with the module names that come with Python. For example, if the system comes with a sys module, its own module cannot be named sys.py, otherwise it will not be able to import the sys module that comes with the system.

 

2. Using modules

Python itself has a lot of very useful modules built-in, as long as the installation is complete, these modules can be used immediately.

Let's take the built-in sysmodule as an example and write a hellomodule:

#!/usr/bin/env python3 
# -*- coding: utf-8 -*-

' a test module '

__author__ = 'Michael Liao'

import sys

def test():
    args = sys.argv    # The argv parameter uses a list to store all the parameters of the command line 
    if len(args)==1: #When   the length of the list is 1, that is, there is only one parameter 
        print ( ' Hello, world! ' )
     elif len(args )==2: #When the command line has two arguments 
        print ( ' Hello, %s! ' % args[1 ])
     else :
         print ( ' Too many arguments! ' )

if __name__=='__main__':
    test()

Lines 1 and 2 are standard comments, the first line of comments allows the hello.py file to run directly on Unix/Linux/Mac, and the second line of comments indicates that the .py file itself uses standard UTF-8 encoding;

Line 4 is a string representing the module's documentation comment, the first string of any module code is considered the module's documentation comment;

Line 6 uses a __author__variable to write the author in, so that when you make the source code public, others can look up to your name;

The above is the standard file template of the Python module. Of course, it can be deleted and not written, but it is definitely not wrong to follow the standard.

This is where the real code begins.

You may have noticed that systhe first step in using a module is to import the module:

import sys

After importing the sysmodule, we have a variable syspointing to the module, and using the sys variable, we can access all the functions of the sys module.

sysThe module has a argvvariable that liststores all the arguments on the command line. argvAt least one element, because the first argument is always the name of the .py file, for example:

python3 hello.pyWhat you get from running sys.argvis ['hello.py'], note that this is python3not a parameter;

That's what you python3 hello.py Michaelget when you run it .sys.argv['hello.py', 'Michael]

Finally, notice these two lines of code:

if __name__=='__main__':
    test()

当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。

我们可以用命令行运行hello.py看看效果:

$ python3 hello.py
Hello, world!
$ python hello.py Michael
Hello, Michael!

如果启动Python交互环境,再导入hello模块:

>>> import hello
>>>

导入时,没有打印Hello, word!,因为没有执行test()函数。

调用hello.test()时,才能打印出Hello, word!

>>> hello.test()
Hello, world!

       

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324608796&siteId=291194637