Modules and packages of Python basic knowledge (3)

Modules and packages

Target
module
package
release module

01. Module

1.1 The concept of modules

Module is a core concept of Python program architecture

  • Every Python source code file ending with the extension py is a module
  • The module name is also an identifier and needs to conform to the naming rules for identifiers
  • The global variables, functions, and classes defined in the module are all tools provided to the outside world for direct use
  • A module is like a toolkit. If you want to use the tools in this toolkit, you need to import this module first

1.2 Two ways to import modules

1) import

import 模块名1, 模块名2

Tip: When importing a module, each import should be on its own line

import 模块名1
import 模块名2

After the introduction, the Module names using tools provided by the module - global variable, function, class

If the name of the module is too long, you can use as to specify the name of the module to facilitate use in the code (use as to specify the alias of the module)

import 模块名1 as 模块别名

Note: the module alias should conform to the big camel case nomenclature
2) from...import import
If you want to import some tools from a certain module, you can use from...import

The import module name is to import all the tools in the module at one time, and access through the module name/alias

# 从 模块 导入 某一个工具
from 模块名1 import 工具名

After importing not required by the module name.

You can directly use the tools provided by the module-global variables, functions, classes

note

If two modules have a function with the same name, the function imported later in the module will overwrite the function imported first

Import code should be written uniformly at the top of the code during development to make it easier to find conflicts in time

Once you find a conflict, you can use the as keyword to give an alias to one of the tools

from...import *(知道)
# 从 模块 导入 所有工具
from 模块名1 import *

note

This method is not recommended, because there is no prompt for the same function name, and it is difficult to troubleshoot problems.

Search path

When you import a module, the order in which the Python parser searches for module positions is:

1. The current directory

2. If it is not in the current directory, Python searches each directory under the shell variable PYTHONPATH.

3. If none is found, Python will check the default path. Under UNIX, the default path is generally /usr/local/lib/python/.

The module search path is stored in the sys.path variable of the system module. The variables include the current directory, PYTHONPATH and the default directory determined by the installation process.


PYTHONPATH variable

As an environment variable, PYTHONPATH consists of many directories installed in a list. The syntax of PYTHONPATH is the same as that of the shell variable PATH.

在 Windows 系统,典型的 PYTHONPATH 如下:
set PYTHONPATH=c:\python27\lib;
在 UNIX 系统,典型的 PYTHONPATH 如下:
set PYTHONPATH=/usr/local/lib/python

_ Name_ property

The _name_ attribute can be done, the code of the test module is only run under test conditions, and will not be executed when imported!

name is Python's built-in attribute, a record of a string
if that is imported to other files , _ name_ is the module name
If you are currently executing program _ name_ is _ main_
in many Python file will see the code in the following format:

# 导入模块
# 定义全局变量
# 定义类
# 定义函数# 在代码的最下方
def main():
   # ...
   pass# 根据 __name__ 判断是否执行下方代码
if __name__ == "__main__":
   main()

Namespace and scope

Variables are names (identifiers) that have matching objects. A namespace is a dictionary containing variable names (keys) and their respective objects (values).

A Python expression can access variables in the local namespace and the global namespace. If a local variable and a global variable have the same name, the local variable will overwrite the global variable.

Each function has its own namespace. The scoping rules of class methods are the same as those of normal functions.

Python will intelligently guess whether a variable is local or global. It assumes that any variable assigned in the function is local.

Therefore, if you want to assign a value to a global variable in a function, you must use the global statement.
The expression of global VarName tells Python that VarName is a global variable so that Python will not look for this variable in the local namespace.

For example, we define a variable Money in the global namespace. We then assign a value to the variable Money in the function, and then Python will assume that Money is a local variable. However, we did not declare a local variable Money before accessing, and as a result, an UnboundLocalError error would occur. This problem can be solved by canceling the comment before the global statement.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
Money = 2000
def AddMoney():
   # 想改正代码就取消以下注释:
   # global Money
   Money = Money + 1
 
print Money
AddMoney()
print Money

dir() function

The dir() function is a sorted list of strings, the content is a name defined in a module.
The returned list contains all modules, variables and functions defined in a module. A simple example is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 导入内置math模块
import math
 
content = dir(math)
 
print content;

The output of the above example:

['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 
'sqrt', 'tan', 'tanh']

Here, the special string variable __name__ points to the name of the module, and __file__ points to the import file name of the module.

globals() and locals() functions

Depending on where it is called, the globals() and locals() functions can be used to return names in the global and local namespaces.

If you call locals() inside a function, all the names that can be accessed in the function are returned.

If you call globals() inside a function, all the global names that can be accessed in the function are returned.

The return types of both functions are dictionaries. So the names can be extracted with the keys() function.

reload() function

When a module is imported into a script, the code in the top part of the module will only be executed once.
Therefore, if you want to re-execute the top-level code in the module, you can use the reload() function. This function will re-import the previously imported module. The syntax is as follows:

reload(module_name)

Here, module_name should directly put the name of the module, not a string form. For example, if you want to reload the hello module, as follows:

reload(hello)

Packages in Python

A package is a hierarchical file directory structure, which defines a Python application environment composed of modules, sub-packages, and sub-packages under sub-packages.

Simply put, a package is a folder, but there must be an _init_.py file in the folder, and the content of the file can be empty. _ init_.py is used to identify the current folder is a package.

Consider a runoob1.py, runoob2.py, _init_.py file in the package_runoob directory , test.py is the code of the test call package, and the directory structure is as follows:

test.py
package_runoob
|-- __init__.py
|-- runoob1.py
|-- runoob2.py

The source code is as follows:

package_runoob/runoob1.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def runoob1():
   print "I'm in runoob1"
package_runoob/runoob2.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
def runoob2():
   print "I'm in runoob2"

Now, create _ init_ .py in the package_runoob directory :

package_runoob/__init__.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
if __name__ == '__main__':
    print '作为主程序运行'
else:
    print 'package_runoob 初始化'

Then we create test.py in the same level directory of package_runoob to call

package_runoob 包
test.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 导入 Phone 包
from package_runoob.runoob1 import runoob1
from package_runoob.runoob2 import runoob2
 
runoob1()
runoob2()
以上实例输出结果:
package_runoob 初始化
I'm in runoob1
I'm in runoob2

As above, for the sake of example, we only put one function in each file, but in fact you can put many functions. You can also define Python classes in these files, and then build a package for these classes.

03. Publish the module (know)

If you want to share the module developed by yourself with others, you can follow the steps below

3.1 Steps to make and release compressed package

  1. Create setup.py
    setup.py file
from distutils.core import setup
​
setup(name="hm_message",  # 包名
     version="1.0",  # 版本
     description="itheima's 发送和接收消息模块",  # 描述信息
     long_description="完整的发送和接收消息模块",  # 完整描述信息
     author="itheima",  # 作者
     author_email="[email protected]",  # 作者邮箱
     url="www.itheima.com",  # 主页
     py_modules=["hm_message.send_message",
                 "hm_message.receive_message"])


For more information about the parameters of the dictionary, you can refer to the official website:

https://docs.python.org/2/distutils/apiref.html

2) Building modules

$ python3 setup.py build

3) Generate a release compressed package

$ python3 setup.py sdist

Note: Which version of the module needs to be made is executed by which version of the interpreter!

3.2 Install the module

$ tar -zxvf hm_message-1.0.tar.gz
​
$ sudo python3 setup.py install

Uninstall the module

Directly from the installation directory, delete the directory where the module is installed.

$ cd /usr/local/lib/python3.5/dist-packages/
$ sudo rm -r hm_message*

3.3 pip install third-party modules

Third-party modules usually refer to Python packages/modules developed by well-known third-party teams and widely used by programmers

For example, pygame is a very mature game development module

pip is a modern, general-purpose Python package management tool

Provides functions such as searching, downloading, installing, and uninstalling Python packages

The installation and uninstallation commands are as follows:

# 将模块安装到 Python 2.x 环境
$ sudo pip install pygame
$ sudo pip uninstall pygame
​
# 将模块安装到 Python 3.x 环境
$ sudo pip3 install pygame
$ sudo pip3 uninstall pygame

Install iPython on Mac

$ sudo pip install ipython

Install iPython under Linux

$ sudo apt install ipython
$ sudo apt install ipython3

Guess you like

Origin blog.csdn.net/weixin_42272869/article/details/113376528