Python modules, packages, files, exceptions, higher-order functions

Table of contents

1. Module

2 bags

3. Documentation

4. Abnormal

5. Higher order functions


1. Module

1.1 Concept

A Python module (Module) is a Python file ending in .py that contains Python object definitions and Python statements. Modules can define functions, classes, variables, and can contain executable code

1.2 Import module

Method 1:

import 模块名 (as 别名)
# 使用模块语法:
模块名(别名).功能

Method 2:

from 模块名 import 功能名 (as 别名)
# 使用模块语法:
功能

Method 3:

from 模块名 import *
# 使用模块语法:
功能

   __all__ list syntax: __all__ = [function 1, function 2...]
   Note : use the from module name import * method to import modules, only the function modules in the __all__ list can be imported

2 bags

There will be a default file __init__.py file in the package [controlling the import behavior of the package]

2.1 Concept

A package organizes related modules together and puts them in the same folder. This folder is called a package.

2.2 Import package

Method 1:

import 包名.模块名
# 调用
包名.模块名.功能
    
import 包名.模块名 as 别名
# 调用
别名.功能

Method 2:

from 包名.模块名 import 功能名
# 调用
功能

from 模块名 import 功能名 as 别名
# 调用
别名.功能

Method 3:

from 包名 import *
# 调用
模块名.功能

 Note: You can add __all__ = [] in the __init__.py file to control the list of modules that are allowed to be imported

3. Documentation

3.1 Opening a file

In Python, use the open() function to open an existing file or create a new file

# 语法
f = open(name, mode,encoding="UTF-8")


# 用的最多的形式
# 如果文件不存在  自动创建
with open('a.txt','a',encoding='utf-8') as f:
    f.write("\nhello")

  --name: is the string of the target file name to be opened (can include the specific path where the file is located)
  --mode: set the mode of opening the file (access mode), read-only read, write write, append append, binary binary etc., mainly "r", "w", "a", "b"
  --encoding: encoding method [if it is binary or other types of data, the default is, and the encoding is not specially set]

3.2 Close the file : f.close()

3.3 File reading and writing

① read:

  --read(num): num indicates the length of the data read from the file (in bytes). If num is not passed in, it means to read all the data in the file --readline(): read only
  once Take a line and encounter '\n' and return
  --readlines(): read the entire file and return a list, one line per element

②Write: write("content")

If you write to an existing file, the original content in the file will be overwritten. At this time, you can use append to append the content

4. Abnormal

4.1 Handling exceptions

① Capture the specified exception type:

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

②Catch multiple specified exceptions:

try:
    可能发生错误的代码
except (异常类型1,异常类型2):
    如果出现异常执行的代码

③Catch all exceptions:

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

④ Abnormal capture information:

try:
    可能发生错误的代码
except 异常类型 as result:
    如果出现异常执行的代码
    #result为异常的信息

4.2 Abnormal else

try:
	可能发生错误的代码
except Exception:
	如果出现异常执行的代码
else:
	没有异常时执行的代码

4.3 Abnormal finally

try:
	可能发生错误的代码
except Exception:
	如果出现异常执行的代码
else:
	没有异常时执行的代码
finally:
	无论是否有异常都要执行的代码

4.4 Custom exceptions

①The custom class inherits Exception
    and rewrites __init__
    and rewrites __str__
        to set the description information of the thrown exception
. ②Use [raise custom exception class] to catch exceptions

    Case: Determine the length of the input string, and report an error if it is less than the specified length

class ShortInputException(Exception):
 
    def __init__(self, length, least_length):
        super().__init__()
        self.length = length
        self.least_length = least_length
 
    def __str__(self):
        return '您输入的长度为:{},最短长度为:{}'.format(self.length, self.least_length)
 
 
try:
    content = input('请输入内容:')
    if len(content) < 5:
        raise ShortInputException(len(content), 5)
    else:
        print('符合要求')
except ShortInputException as e:
    print(e)
'''
请输入内容:ASD
您输入的长度为:3,最短长度为:5
'''

5. Higher order functions

5.1 Concept

Passing a function as a parameter into another function is called a higher-order function, which is the embodiment of functional programming

5.2 Built-in functions

abs(): find the absolute value of the number
round(): round the number

5.3 Built-in higher-order functions

①map()
    map(func,lst): Apply the incoming function variable func to each element of the lst variable, and form the result into a new list
    Case: Calculate the 2 power of each number in the lst sequence

func = lambda a:a*a
# map函数  接收几个值  就给出几个值
lst = [1,2,3,4,5,6,7,8]
m = map(func,lst)   # [1,4,9.....]
for i in m:
    print(i)

②reduce()
    reduce(func, lst), where func must have two parameters, and the result of each func calculation continues to be accumulated with the next element of the sequence. Note: before
    using the reduce() function, the module functools must be imported
    . Example: Calculate the cumulative sum of each number in the lst sequence

from functools import reduce as r

func = lambda a,b:a+b
lst = [1,2,3,4,5,6,7,8]
print(r(func,lst))

③filter()
    The filter(func,lst) function is used to filter the sequence, filter out elements that do not meet the conditions, and return a filter object, which can be converted into a list

    Case: Take out the even numbers in the lst sequence

lst = [1, 2, 3, 4, 5, 6, 7, 8]
def func(n):
    if n % 2 == 0:
        return True
    return False

f = filter(func, lst)
for i in f:
    print(i)

 That's all for today's learning record, bye!

Description: Learning records, if there are mistakes, please correct me, if you have any questions, welcome to comment

Guess you like

Origin blog.csdn.net/qq_52445443/article/details/122813357