day14 - decorators and modules

day14 - decorators and modules (10.8)

Knowledge outline:

1. Decorator
2. Module (import of modules and packages, use of system modules)
3. Modules: math,random,time\datetime - (time management) is very important, OS - (file and file plus management) is important, os.path() module
4. hashlib - learn

1. Add functionality to functions

Function of decorator: add new functions to the written functions

  1. Add new functions to the function scheme 1: directly modify the original function and add the new functions
    Existing problems: if multiple functions need to add the same function, the code of the same function needs to be written multiple times
import time
from random import randint
def download(name):
    start = time.time()
    print(f'{name}Start downloading')
    time.sleep(randint(1, 3))
    print(f'{name}End of download')
    end = time.time()
    print(f'Total time:{end-start}s')


def func1():
    start = time.time()
    num1 = float(input('Please enter the number 1:'))
    num2 = float(input('Please enter the number 2:'))
    print(f'{num1} + {num2} = {num1 + num2}')
    end = time.time()
    print(f'Total time:{end - start}s')

# download('alive ')
# func1()

# Demand: add function, (print movie download duration)


# Scheme 2: real parameter higher-order function
def download2(name='Movie 1'):
    print(f'{name}Start downloading')
    time.sleep(randint(1, 3))
    print(f'{name}End of download')


def func12():
    num1 = float(input('Please enter the number 1:'))
    num2 = float(input('Please enter the number 2:'))
    print(f'{num1} + {num2} = {num1 + num2}')


def func22():
    print('hello world!')


# def logo(fn):
#     fn()
#     print('qianfeng education! ')


# def total_time(fn):
#     start = time.time()
#     # Realize the function of the original function
#     fn()
#     end = time.time()
#     print(f 'total time: {end - start}s')

# download2()
# func12()
# total_time(func22)
# total_time(download2)
# total_time(func12)
# total_time(func22)

# logo(func22)
# Scheme 3: use decorator**
# Decorator = argument higher-order function + return value higher-order function + sugar syntax
def total_time(fn):
    def new_fn():
        start = time.time()
        fn()
        end = time.time()
        print(f'Total time:{end - start}s')
    return new_fn


def logo(fn):
    def new_fn():
        fn()
        print('Qianfeng Education')
    return  new_fn


@logo
def download3(name='Movie 1'):
    print(f'{name}Start downloading')
    time.sleep(randint(1, 3))
    print(f'{name}End of download')


@total_time
def func12():
    num1 = float(input('Please enter the number 1:'))
    num2 = float(input('Please enter the number 2:'))
    print(f'{num1} + {num2} = {num1 + num2}')


download3()
func12()

2. Decorator syntax

# Decorator = argument higher-order function + return value higher-order function + sugar syntax
# 1. Fixed structure
"""
def Decorator name(Old (original) function):  # #New function, old function name optional
    def New function(*args, **kwargs): #  # Any parameter, number, location parameter, keyword parameter
        result = Old function(*args, **kwargs)
        Realize new functions
        return result
    return New function
"""
use@Principle of using decorator:
import time
def add_logo(fn):
    def new_fn(*args, **kwargs):
        result = fn(*args, **kwargs)
        print('Qianfeng Education!')
        return result
    return new_fn


@add_logo
def func():
    print('hello world!')


@add_logo
def func1(x):
    print(x * 2)


@add_logo     # func2 = add_logo(func2)
def func2():
    return 100

func()

func1(100)
func1(x=200)

print(func2())


# Exercise 1: write a decorator that counts the execution time of a function
def total_time(fn):
    def new_fn(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        end = time.time()
        print(f'Total time:{end - start}')
        return result
    return new_fn


# Exercise 2: write a decorator and print start at the beginning of the original function
def add_start(fn):
    def new_fn(*args, **kwargs):
        print('start!')
        result = fn(*args, **kwargs)
        return result
    return new_fn


# Exercise 3: change the return value of a function whose return value is a number to 10000 times the original value
def blow_up(fn):
    def new_fn(*args, **kwargs):
        result = fn(*args, **kwargs)
        if type(result) in (int, float):
            return result * 10000
        return result
    return new_fn

3. Module import

  1. modular

A py file is a module

You can use content from one module to another,
Prerequisites: 1) the name of the module used by another module must meet the requirements of variable name; 2) it needs to be imported before being used

  1. Import module (important)
    """
    1) Import module name - directly import the specified module. After import, you can use all global variables in the module through "module name". "
    2) from module name import variable name 1, variable name 2, variable name 3,... - import the specified variable through the module, and directly use the specified variable after import
    3) from module name import * - import all global variables in the module through the module, and use the variables directly after import
    4) Rename
    import module name as new module name - use the new module name when using the module
    from module name import variable name 1 as new variable name 1, variable name 2, variable name 3
    """
# =================Import method 1==================
# import test1
# print(test1.a)
# print(test1.x)
# test1.func1()
#
# import random
# random.randint(10, 20)

# =================Import method 2==================
# from test1 import a, func1
# print(a)
# func1()
# # print(x)      # NameError: name 'x' is not defined

# =================Import method 3==================
# from test1 import *
# print(a)
# print(x)
# func1()

# =================Import method 4==================
# import test1 as ts1
# # import numpy as np
# # import pandas as pd
#
# test1 = 'hello'
#
# print(test1, ts1.a)
# ts1.func1()


from test1 import x as t_x, a

x = 'Xiao Ming'

print(x, t_x)
print(a)

4. Principle of import module

  1. principle
    """
    When the code is executed into the import module, the system will automatically enter the module and execute all the codes in the module
    """
  2. Features of this if statement: the code in the if statement will not be executed when the current module is imported by another module; if the current module is run directly, it will be executed again
from download_file import download_film

print(f'04:{__name__}')
download_film('Léon')


# Features of this if statement: the code in the if statement will not be executed when the current module is imported by another module; if the current module is run directly, it will be executed again
if __name__ == '__main__':
    pass

5. Import of packages

# 1. Import modules in the package (important)
"""
1) import Package name        -       To modify__init__.py Documents are meaningful, otherwise they are useless
2) import Package name.Module name
3) from Package name import Module name 1, Module name 2,...
4) from Package name.Module name import Variable 1, Variable 2,...
"""
# =============Import method 1=============
# import fileManager

# =============Import method 2=============
# a. Do not rename
# import fileManager.csvFile
# print(fileManager.csvFile.aa)
# fileManager.csvFile.read_file()

# b. Rename
# import fileManager.csvFile as csvFile
# print(csvFile.aa)
# csvFile.read_file()


# =============Import method 3=============
# from fileManager import csvFile, jsonFile
# print(csvFile.aa)
# jsonFile.write_dict()

# =============Import method 4=============
# from fileManager.csvFile import read_file
# read_file()
2. How to import packages
# When importing the contents of the modules in the package, the system will first execute the contents in the _init_.py file in the package, and then execute the contents in the modules
# from fileManager import csvFile

# Function one
# import fileManager
# fileManager.csvFile.read_file()
# fileManager.jsonFile.write_dict()

# Function two
# from fileManager.jsonFile import write_dict

# from fileManager import write_dict
# write_dict()

# import fileManager
# fileManager.write_dict()
# fileManager.open_file()

from fileManager import open_file, write_dict
open_file()

6. Mathematical module

math - mathematical function related to ordinary numbers
cmath - complex dependent data function

Ordinary numbers (int, float): 100, - 23.8, 0.23
Complex: a+bj (a-real part, b-imaginary part and j are imaginary units; j**2 == -1)

x = 10 + 2j
y = 20 - 3j
print(type(x))
print(x + y)     # 30 - 1j
print(x * y)     # 206 + 10j
  1. Ceil (floating point number) - converts a floating point number to an integer (rounded to the largest)
print(math.ceil(1.9))
print(math.ceil(1.1))
  1. Floor - converts a floating-point number to an integer (rounded to the small)
print(math.floor(1.9))    # 1
print(math.floor(1.1))    # 1
  1. Round - converts a floating-point number to an integer (rounded)
print(round(1.9))       # 2
print(round(1.1))       # 1

randrange(M,N,step) - random integer

import random

# randrange(M,N,step) - random integer
print(random.randrange(10, 20, 2))

randint(M, N) - random integer

print(random.randint(10, 20))

random() - generate random decimal from 0 to 1

print(random.random())   # 0 ~ 1
print(random.random() * 10)     # 0 ~ 10
print(random.random() * 9 + 1)     #  1 ~ 10

Choices (sequence, k = number) - randomly get a specified number of elements from the sequence (with put back extraction)
Choice - gets an element at random from the sequence

nums = [1, 2, 3, 4, 5]
print(random.choices(nums, k=4))

Sample (sequence, k = quantity) - randomly obtains a specified number of elements from the sequence (no put back extraction)

print(random.sample(nums, k=4))

Shuffle - randomly shuffle the order of the elements in the list

random.shuffle(nums)
print(nums)

7. Time module

1. Get the current time
Time stamp: record a time based on the time difference between the current time and 0:0:0:0 (Greenwich mean time) on January 1, 1970 (the unit of time difference is seconds)

import time
import datetime
t1 = time.time()
print(t1)

'2021 October 8, 2016:56:00'
# 1633683338.1856189
  1. Get local time
    localtime() - get the current local time (the return value is the structure time)
t2 = time.localtime()
print(t2, t2.tm_year)

Localtime (timestamp) - go back to the local time corresponding to the specified timestamp

t3 = time.localtime(0)
print(t3)

t4 = time.localtime(1633683338.1856189)
print(t4)
  1. Sleep - pause the program
    Sleep - time in seconds
time.sleep(2)
print('==================')

4. Convert structure time to timestamp
Mktime (structure time)

t5 = time.mktime(t2)
print(t5)

8. Other py documents

download_file.py


def download_film(name):
    print(f'------------{name}Start downloading------------')
    print('Detect network status')
    print('Connect server')
    print(f'Transfer data:{name}')
    print('Save data!')
    print(f'{name}Download complete!')


# Features of this if statement: the code in the if statement will not be executed when the current module is imported by another module; if the current module is run directly, it will be executed again
print(f'download_file:{__name__}')
if __name__ == '__main__':
    download_film('Pirates of the Caribbean 1')
    download_film('Vampire Diaries')
    download_film('The Avengers')

    sum1 = 1
    for x in range(1, 21):
        sum1 *= x
    print(sum1)

test1.py

print('test1 Start execution')
a = 100

for x in range(3):
    print(f'x:{x}')


def func1():
    print('test1 Functions in')


print('test1 End execution')

9. How to create a package

# python package package
# Built in _init _. PY
# directory put folder
# Add _init _. Py to become a package

fileManager package

__init__.py

print('Package__init__Executed')

# Function 1: import all modules in the package, so that all modules in the package can be used through the package when importing the package directly from the outside
from fileManager import csvFile, jsonFile, textFile

# Function 2: establish shortcut keys for common methods and data
# write_dict = jsonFile.write_dict
from fileManager.jsonFile import write_dict # By importing package functions


# Function 3: encapsulating general functions
def open_file():
    print('Open file')
csvFile.py

print('csvFile Start execution')
aa = 100


def read_file():
    print('obtain csv File content')


print('csvFile end of execution')
jsonFile.py

bb = 200


def write_dict():
    print('Write dictionary to json In the file')
textFile.py

cc = 300


def del_file():
    print('Delete text file')

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-eUt6iASD-1633691037563)(C:\Users\z\Desktop\tupian.81.png)]

ager import csvFile, jsonFile, textFile

Function 2: establish shortcut keys for common methods and data

write_dict = jsonFile.write_dict

from fileManager.jsonFile import write_dict # by importing package functions

Function 3: encapsulating general functions

def open_file():
print('open file ')

```python
csvFile.py

print('csvFile Start execution')
aa = 100


def read_file():
    print('obtain csv File content')


print('csvFile end of execution')
jsonFile.py

bb = 200


def write_dict():
    print('Write dictionary to json In the file')
textFile.py

cc = 300


def del_file():
    print('Delete text file')

[external chain picture transferring... (img-eUt6iASD-1633691037563)]

Keywords: Python Rust

Added by aaronfenker on Fri, 08 Oct 2021 13:47:13 +0300