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

catalogue

1. Module

2. Package

3. Documents

4. Abnormal

5. Higher order function

1. Module

1.1 concept

Python module is a python file, which is written in py ends with Python object definitions and python statements. Modules can define functions, classes, variables, and can also contain executable code

1.2 import module

Mode 1:

import Module name (as alias)
# Use module syntax:
Module name(alias).function

Mode 2:

from Module name import Function name (as alias)
# Use module syntax:
function

Mode 3:

from Module name import *
# Use module syntax:
function

   __ all__ List syntax:__ all__ = [function 1, function 2...]
Note: you can only import modules by using the from module name import *__ all__ Function modules in the list

2. Package

There will be a default file in the package__ init__.py file [controls the import of packages]

2.1 concept

Packages organize related modules together and put them in the same folder, which is called packages.

2.2 import package

Mode 1:

import Package name.Module name
# call
 Package name.Module name.function
    
import Package name.Module name as alias
# call
 alias.function

Mode 2:

from Package name.Module name import Function name
# call
 function

from Module name import Function name as alias
# call
 alias.function

Mode 3:

from Package name import *
# call
 Module name.function

Note: you can__ init__. Add to py file__ all__ = Control module import allowed list

3. Documents

3.1 opening files

In Python, using the open() function, you can open an existing file or create a new file

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


# The most used form
# If the file does not exist, it is created automatically
with open('a.txt','a',encoding='utf-8') as f:
    f.write("\nhello")

-- Name: is the string of the name of the target file 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, append, binary binary, etc., mainly "r","w","a","b"
-- encoding: encoding method [if it is binary or other types of data, it is the default, and the encoding is not specially set]

3.2 close file: f.close()

3.3 document 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(): only one line is read at a time, and '\ n' is returned
-- readlines(): read the entire file and return the list, one element at a time

② Write: write("content")

If you write 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

① Catch specified exception type:

try: 
    Possible error codes
except Exception type:
    Code to execute if an exception occurs

② Catch multiple specified exceptions:

try: 
    Possible error codes
except (Exception type 1, exception type 2): 
    Code to execute if an exception occurs

③ Catch all exceptions:

try: 
    Possible error codes
except Exception: 
    Code to execute if an exception occurs

④ Exception capture information:

try: 
    Possible error codes
except Exception type as result: 
    Code to execute if an exception occurs
    #result is the exception information

4.2 abnormal else

try: 
	Possible error codes
except Exception: 
	Code to execute if an exception occurs
else:
	Code executed when there are no exceptions

4.3 finally of exception

try: 
	Possible error codes
except Exception: 
	Code to execute if an exception occurs
else:
	Code executed when there are no exceptions
finally: 
	Code to execute whether there are exceptions or not

4.4 custom exception

① Custom class inherits Exception
Rewrite__ init__
Rewrite__ str__
Sets the description of the exception thrown
② Use [raise custom exception class] to catch exceptions

Case: judge the length of the input string. If it is less than the specified length, an error will be reported

class ShortInputException(Exception):
 
    def __init__(self, length, least_length):
        super().__init__()
        self.length = length
        self.least_length = least_length
 
    def __str__(self):
        return 'The length you entered is:{},The minimum length is:{}'.format(self.length, self.least_length)
 
 
try:
    content = input('Please enter the content:')
    if len(content) < 5:
        raise ShortInputException(len(content), 5)
    else:
        print('Meet the requirements')
except ShortInputException as e:
    print(e)
'''
Please enter the content:ASD
 The length you entered is:3,The minimum length is:5
'''

5. Higher order function

5.1 concept

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

5.2 built in functions

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

5.3 built in high-order function

①map()
map(func,lst): apply the passed in function variable func to each element of lst variable, and form a new list of results
Case: calculate the 2nd power of each number in lst sequence

func = lambda a:a*a
# The map function receives several values and gives several values
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. The result of each func calculation continues to accumulate with the next element of the sequence
Note: before using the reduce() function, you must import the module functools
Case: calculate the cumulative sum of each number in 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 the elements that do not meet the conditions, and return a filter object, which can be converted into a list

Case: take out even numbers in 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 study record. Bye!

Note: if there is any mistake in the learning record, please correct it. If there is any doubt, please comment

Keywords: Python Back-end

Added by tbaink2000 on Mon, 07 Feb 2022 20:25:53 +0200