Python from entry to practice: the use of modules

Table of contents

1. Module introduction

Second, the use of modules

2.1import

2.2from-import

2.3 as

 2.4 Path and priority of search modules

2.5 Distinguish between the two uses of py files


1. Module introduction

Modularizing the program will make the organizational structure of the program clear and easier to maintain. The use of modules not only ensures the reusability of the code, but also enhances the structure and maintainability of the program. In addition to custom modules, we can also import ready-made functions provided by built-in or third-party modules, which greatly improves the efficiency of programming and also reflects the idea of ​​​​"avoiding repeated wheel creation"!

Second, the use of modules

2.1 import

#文件名:foo.py
x=1
def get():
    print(x)
def change():
    global x
    x=0
class Foo:
    def func(self):
       print('from the func')

If you want to refer to the function in foo.py in another py file, you need to use import foo. The first time you import a module, you will do three things:

1. Execute the source file code

2. Generate a new namespace for storing the name generated during the execution of the source file

3. Obtain a name foo in the name space where the current execution file is located, which points to the newly created module name space. If you want to refer to the name in the module name space, you need to add the prefix, as follows

import foo #导入模块foo
a=foo.x #引用模块foo中变量x的值赋值给当前名称空间中的名字a
foo.get() #调用模块foo的get函数
foo.change() #调用模块foo中的change函数
obj=foo.Foo() #使用模块foo的类Foo来实例化,进一步可以执行obj.func()

It should be emphasized that the module has been loaded into the memory space for the first time, and subsequent repeated imports will directly refer to the existing modules in the memory, and will not repeatedly execute the file. By importing sys, printing the value of sys.modules can be See the names of modules already loaded in memory.

#在Python中模块也属于第一类对象,可以进行赋值、以数据形式传递以及作为容器类型的元素等操作。

2.2from-import

The from...import statement is basically the same, the only difference is: after using import foo to import the module, the name in the reference module needs to be prefixed with foo., and use from foo import to access the name in the reference module foo, as follows

from foo import * #把foo中所有的名字都导入到当前执行文件的名称空间中,在当前位置直接可以使用这些名字
 
a=x
get()
change()
obj=Foo() 

If we need to refer to too many names in the module, we can use the above import form to achieve the effect of saving code, but one point to be emphasized is: it can only be imported at the top level of the module, and it is illegal in the function. And the method will bring a side effect, that is, we can't figure out which names are imported from the source file to the current location, which is very likely to conflict with the name of the current location. The writer of the module can define the _all_ variable in his own file to control the meaning of *

#foo.py
__all__=['x','get'] #该列表中所有的元素必须是字符串类型,每个元素对应foo.py中的一个名字
x=1
def get():
    print(x)
def change():
    global x
    x=0
class Foo:
    def func(self):
       print('from the func')

 In this way, when we use * import in another file, we can only import the names defined by _all_

2.3 as

import foo as f #为导入的模块foo在当前位置起别名f,以后再使用时就用这个别名f
f.x
f.get()

Usually, when the imported name is too long, aliasing is used to simplify the code. In addition, aliasing the imported name can avoid conflicts with the current name. Another important point is: the calling method can be kept Consistency . For example, we have two modules, json and pickle, that implement the load method at the same time. The function is to parse structured data from an open file, but the format of the parsing is different. You can use the following code to selectively load different the module

if data_format == 'json':
    import json as serialize #如果数据格式是json,那么导入json模块并命名为serialize
elif data_format == 'pickle':
    import pickle as serialize #如果数据格式是pickle,那么导入pickle模块并命名为serialize
 
data=serialize.load(fn) #最终调用的方式是一致的

 2.4 Path and priority of search modules

When importing a module, if the module has been loaded into the memory, it will be directly referenced, otherwise, the built-in module will be searched first, and then the path defined in sys.path will be searched in order from left to right until the file corresponding to the module is found , otherwise an exception is thrown. sys.path is also known as the module search path, it is a list type

The first path in sys.path is usually empty, representing the path where the executable file is located, so it must be imported normally when the imported module and the executable file are in the same directory, and for the imported module and the executable file in In the case of different paths, in order to ensure that the source file corresponding to the module can still be found, the path where the source file foo.py is located needs to be added to sys.path, assuming that the path where foo.py is located is /pythoner/projects/

2.5 Distinguish between the two uses of py files

A Python file has two purposes, one is executed as the main program/script, and the other is imported as a module. In order to distinguish the different purposes of the same file, each py file has a built-in _name_ variable, which is in The py file is assigned the value "_main_" when it is executed as a script, and the module name is assigned when the py file is imported as a module

#foo.py
...
if __name__ == '__main__':
    foo.py被当做脚本执行时运行的代码
else:
    foo.py被当做模块导入时运行的代码

Usually we write test code for module functions in the sub-code block of if, so that when foo.py is run as a script, it will execute the test code, but when it is imported as a module, it does not need to execute the test code.

Guess you like

Origin blog.csdn.net/weixin_43507744/article/details/126591413