Python study notes | 4 Exceptions, modules and packages

Python | 4 Exceptions, Modules and Packages

Contents of this chapter: Exceptions (bugs), modules and packages in Python.

All relevant codes can be viewed at https://github.com/hzyao/Python-Cookbook .
It’s wonderful to learn and practice at the same time, and to discover in time! It may taste better if eaten together!

Exceptions, modules and packages

1 exception

When an error is detected, the Python interpreter will not be able to run, and some error messages will appear. This is the so-called " exception ", which is what we often call " bug ".

Exception: An error occurred while the program was running.

Bug: also known as anomaly, due to historical cases of calculation failure caused by small bugs, it has continued to be used to this day.

Write bug examples yourself! I believe you must have seen a lot of it hahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahaha! ! !

1.1 Exception catching method

There is no perfect program in the world. Abnormalities may occur during the running of any program , that is, bugs may occur that prevent the program from running perfectly.

What we have to do is not to strive for the perfect operation of the program, but to prepare and handle possible bugs in advance within our ability.

This behavior is called exception handling (catching exceptions) .

When our program encounters a bug, there are two situations:

  1. The entire program stopped running because of a bug;
  2. The bug is alerted and the entire program continues to run.

Obviously in the previous study, all our programs will have a situation like 1 when encountering a bug, that is, the entire program will crash directly; but in real work, we certainly cannot let the entire program crash because of a small bug. Crash, that is, what we hope to achieve is the situation of 2. So here we need to use catching exceptions .

The purpose of catching exceptions is to assume in advance that an exception will occur somewhere, be prepared in advance, and provide subsequent solutions when an exception does occur .

Overview:

try:
	可能发生异常的语句
except:
	出现异常的准备手段
else:
	未出现异常时要做的事情
finally:
	不管出不出现异常都会做的事情

Detailed explanation:

  1. Catching regular exceptions

    grammar:

    try:
    	可能发生错误的代码
    except:
    	出现异常执行的代码
    

    example:

    # 捕获常规异常
    try:
        f = open("./data/fake.txt", "r", encoding="UTF-8")
    except:
        print("bug")
        f = open("./data/fake.txt", "w", encoding="UTF-8")
    
  2. Catch the specified exception

    grammar:

    try:
    	可能发生错误的代码
    except TypeError as 别名:
    	出现异常执行的代码
    

    Note:

    1. If the code exception you are trying to execute is inconsistent with the exception type to be caught, the exception cannot be caught;
    2. Generally, tryonly one line of code to try to execute is placed below;
    3. The alias records the specific information of the exception.

    example:

    # 捕获指定异常
    try:
        print(xmy)
    except NameError as e:
        print("bug")
        print(e)
    
    # 无法捕获其他类型异常,直接报错
    try:
        1 / 0
    except NameError as e:
        print("bug")
        print(e)
    
    ---------------------------------------------------------------------------
    ZeroDivisionError                         Traceback (most recent call last)
    /tmp/ipykernel_9715/2479312728.py in 
          1 # 无法捕获其他类型异常,直接报错
          2 try:
    ----> 3     1 / 0
          4 except NameError as e:
          5     print("bug")
    
    ZeroDivisionError: division by zero
    
  3. Catching multiple exceptions

    When catching multiple exceptions, you can put the name of the exception type to be caught at the exceptend and write it in a tuple.

    # 捕获多个异常
    try:
        1 / 0
    except (NameError, ZeroDivisionError) as e:
        print("bug")
        print(e)
    
  4. catch all exceptions

    The syntax in the previous part of catching general exceptions is not limited, and all exceptions can be caught. There are also the following top-level methods:

    # 捕获所有异常
    try:
        1 / 0 # print(name)
    except Exception as e:
        print("bug")
        print(e)
    
  5. Exceptionelse

    elseIndicates the code to be executed if there is no exception.

    # 异常else
    try:
        print("name")
    except Exception as e:
        print("sad")
    else:
        print("happy")
    
  6. Exception finally

    finallyIndicates code that must be executed regardless of whether there is an exception, such as closing a file.

    # 异常finally
    try:
        print("name")
    except Exception as e:
        print("sad")
    else:
        print("happy")
    finally:
        f.close()
    

1.2 Exception delivery

Exceptions are transitive. Note: When all functions do not catch exceptions, the program will report an error.

# 异常的传递性演示
## 定义一个有异常的函数
def func():
    print("func1 start")
    num = 1 / 0 # 异常
    print("func1 over")

## 定义一个无异常的函数,调用上面的函数
def func():
    print("func2 start")
    func1()
    print("func2 over")

## 定义一个主函数,调用上面的函数
def main():
    try:
        func2()
    except Exception as e:
        print("bug")
        print(e)

main()

2 modules

2.1 What is a module

Python module (module): It is a Python file , ending with .py , which contains functions, classes, variables, executable code, etc. In layman's terms, a module is a Python file, which contains classes, functions, variables, etc., which we can use (import the module to use).

Function: There are many different modules in Python. Each module can help us quickly implement some functions . For example, to implement time-related functions, we can use the time module. We can think of a module as a toolkit . Each toolkit has various tools for us to use to achieve various functions.

2.2 How to import modules

The module needs to be imported before use. The syntax is as follows:
[form 模块名] import [模块 | 类 | 变量 | 函数| *] [as 别名]

Common combination forms are as follows:

  • import 模块名
  • from 模块名 import 类、变量、方法等
  • from 模块名 import *
  • import 模块名 as 别名
  • from 模块名 import 功能名 as 别名
  1. import module name

    # 模块导入
    import time
    print("hello")
    time.sleep(3) # 通过 . 就可以使用模块内部的全部功能(类、函数、变量)
    print("hi")
    
  2. from module name import function name

    # 导入模块中的功能
    from time import sleep
    print("hello")
    sleep(3)
    print("hi")
    
  3. from module name import *

    # 使用 * 导入模块中的全部功能
    from time import *
    print("hello")
    sleep(3) # 与上述直接导入模块作用相同,但是使用模块中函数时可直接使用,不需要用 . 
    print("hi")
    
  4. as defines alias

    # 模块定义别名
    import time as t
    t.sleep(2)
    
    # 功能定义别名
    from time import sleep as sl
    sl(2)
    

Note:

  • from can be omitted, just import directly
  • as alias can be omitted
  • Determine the hierarchical relationship by
  • The import of the module is generally written at the beginning of the code file

2.3 Custom modules

Python has helped us implement many modules, but sometimes you may need some personalized modules, which we can implement through custom modules , which means you can make a module yourself. The import method is the same as that of Python built-in modules.

# 导入自定义模块(先自己去构建一个!俺的叫 *mymodule*)
## 我的模块
def test(a, b):
    print(a + b)

## 导入我的模块
import mymodule
mymodule.test(3, 6)

Note: When multiple modules are imported and there are functions with the same name in different modules, the functions of the module imported later will overwrite the functions of the module imported first.

In actual development, after we finish writing a module, in order for the module to achieve the desired effect in the project, we may add test code ( ) to the .py file ourselves test(). testIn this case, whether it is the current file or other files that have imported the module, the function call will be automatically executed when running . We can solve this problem by using in .py file __main__.

if __name__ == "__main__"It means that only when the program is executed directly, it will enter ifthe interior. If it is imported, it ifcannot enter.

# 我的module内容
def test(a, b):
    print(a + b)

# 只在当前文件中调用该函数,其他文件导入此模块则不会调用该函数
if __name__ == "__main__":
    test(1, 1)

__all__If there are variables in a module file , from xxx import *only elements in this list can be imported when using import.

# 自定义模块内容
__all__ = ["test"] # 这样在其他文件中以 * 导入时,就只能使用test函数

def test(a, b):
    print(a + b)

def test_b(a, b):
    print(a - b)

if __name__ == "__main__":
    test(1, 1)

3 pack

3.1 What are Python packages

Physically , a package is a folder , which contains a __init__.pyfile. This folder can be used to store multiple module files (code files); logically , the essence of a package is still a module .

The role of packages: When we have more and more module files, packages can help us manage these modules . The function of a package is to contain multiple modules and group them into one category for ease of use, but the essence of the package is still a module .

3.2 Use of custom Python packages

First of all, it is quite simple to customize a package. Create a folder and create a file under the folder __init__.py(the presence of this file indicates that the folder is a Python package, not an ordinary folder. Pycharm supports automatic creation), and then Just create the module you want! like this:

Insert image description here

The method of importing a custom package is the same as importing a package, as follows:

import 包名.模块名
包名.模块名.目标
# mypkg_module_1.py 中的内容,mypkg_module_2.py 中同,仅把1改为2
"""
module 1

"""

def info_print1():
    print("modele 1")
# 导入自定义包,与导入包方式相同
## 第一种写法
import mypkg.mypkg_module_1
import mypkg.mypkg_module_2

mypkg.mypkg_module_1.info_print1()
mypkg.mypkg_module_2.info_print2()

## 第二种写法
from mypkg import mypkg_module_1
from mypkg import mypkg_module_2

mypkg_module_1.info_print1()
mypkg_module_2.info_print2()

## 第三种写法
from mypkg.mypkg_module_1 import info_print1
from mypkg.mypkg_module_2 import info_print2
info_print1()
info_print2()

In the import package, there are also __all__variables mentioned in the module section before, which have the same function of controlling the imported content as in the module import *. It should be noted that you must __init__.pyadd it to the file __all__ = []to control the list of modules that are allowed to be imported.

from 包名 import * 
模块名.目标
# __init__.py 中的内容,[]中是包中可以用的模块的名字
__all__ = ['mypkg_module_1']
# 导入包2.0
from mypkg import *
mypkg_module_1.info_print1()
mypkg_module_2.info_print2() # 2未被导入,运行会报错

Note: __all__For yes from xxx import *, it is import xxxinvalid for.

Guess you like

Origin blog.csdn.net/weixin_43843918/article/details/131769227