2020_10_14_Decorators, generators and modules

Ginseng decorator

1. The function of a parameter decorator
When adding a function to a function, you can control specific operations through parameters (the operation is not fixed)
2. How to write a parameter decorator
def function name 0 (parameter list of the decorator)
def function name 1 (func):
def function name 2(*args, **kwargs):
result = func(*arges, **kwargs)
new function
return result
return function name 2
return function name 1

def function name (parameter list of
decorator ) no-argument decorator
return function name of no-argument decorator

Usage of parameter decorator:
@function name0 (decorator argument list)

Write a decorator to print any specified prompt message after the function ends
def add_message(msg):
def test1(func):
def new_func(*args, **kwargs):
result = func(*args, **kwargs)
print (msg)
return result
return new_func
return test1

@add_message(‘after')
def func1 (x, y):
print (x + y)

func1(10, 20)

Exercise: Write a decorator that subtracts the specified value from the return value of the original function
@sub(10) @sub(30)
def sub(num):
def test(func):
def new_func(*args, **kwargs ):
result = func(*args, **kwargs)
if type(result) in (int, float, complex):
return result-num
return result
return new_func
return test

Iterator (iter)

1. Iterator is a container data type (sequence).
Features: a. Cannot view all elements at the same time (printing can not see the elements inside)
b. Cannot count the number
c. When obtaining elements, you can only take one by one (each Take the top one at a time), and each time you get an element, the element will disappear from the iterator (if you take one, you will lose one)

2. Create an iterator
There are two ways to create an iterator:
1) Convert other sequences into an iterator through iter
2) Create a generator
iter1 = iter([10, 20, 30, 40])
print(iter1)
print(len (iter1)) # Error!

iter2 = iter(‘hello’)
print(iter2)

3. Get the element
No matter how you get the element in the iterator, the corresponding element will disappear from the iterator.
1) Take a single element
next (iterator)-get the uppermost data of the iterator (if the iterator is Is empty, it will report StopIteration error)

2) Traverse the
for variable in iterator:
pass

print(next(iter1)) # 10
print(next(iter1)) # 20
next(iter1)
print(next(iter1)) # 40
print(next(iter1)) # 报错! StopIteration

for x in iter2:
print(x)

print(next(iter2)) # Report an error! StopIteration

iter3 = iter(‘python!’)
list1 = list(iter3)
print(list1)
print(next(iter3)) # 报错! StopIteration

iter4 = iter(‘python123’)
next(iter4)
for x in iter4:
print(‘x:’, x)

Generator

1. The essence of generators is iterators (the characteristics of iterators and the way generators obtain elements are applicable)

2. How to create a generator
You can create a generator object
by calling a function with the yield keyword (if there is yield in the called function, the function body will not be executed, and the function return value will not be obtained)

def func1():
print(’======’)
print(’++++++’)
yield
return 100

re = func1()
print(re) # <generator object func1 at 0x10d9380d0>

3. How to determine the number of data generated by the generator
"""
: After executing the function corresponding to the generator, you will encounter
the value of the data generated by yield() several times : See the yield each time you encounter What is the data behind? No data is None

def func2():
yield 100
yield ‘abc’
for x in range(3):
yield x

gen1 = func2()
print(gen1)
print(list(gen1)) # [100, ‘abc’, 0, 1, 2]

def func3(x):
yield 10
if x & 1:
yield 20
return 30
yield 30

gen2 = func3(5)
print(list(gen2)) # [10, 20]

gen3 = func3(4)
print(list(gen3)) # [10]

4. The principle of the generator to generate data. The
function body will not be executed when the function is called to create the generator object. It will be executed when the elements in the generator are obtained.
The first time you get an element, it will be executed from the beginning of the function body, and it will stop when the first yield is executed, and the data after the yield will be used as the acquired element this time. Each time you get an element later, it will execute from the position where it ended last time, and the execution will stop until the next yield. If no yield is encountered from the current position to the end of the function, a StopIteration error will be reported if it is next.

def func4():
print(‘1’)
yield 100
print(‘2’)
yield 200
print(‘3’)
yield 300

gen4 = func4()
print(next(gen4))
for _ in range(5):
print(’~~~~~~~~~~’)

print(next(gen4))
print(next(gen4))
print(next(gen4)) # 报错! StopIteration

gen5 = func4()
gen6 = func4()
print(next(gen5)) # 100
print(next(gen5)) # 200
print(next(gen6)) # 100

def func5():
for x in range(5):
yield x*2

print(next(func5())) # 0
print(next(func5())) # 0

Exercise: Write a generator that generates
student IDs , which can generate student IDs from 001 to 999 in the specified subject. python student: python001 ~ python999
java student: java001 ~ java999

def create_num(subject: str):
for x in range(1, 1000):
yield f’{subject}{x:0>3}’
# yield subject+str(x).zfill(3)

python_nums = create_num(‘python’)
print(next(python_nums))
print(next(python_nums))

java_num = create_num(‘java’)
print(next(java_num))

Exercise: Write an even number generator that can generate all positive even numbers
def even_numbers():
num = 2
while True:
yield num
num += 2

even_gen = even_numbers()
for _ in range(100):
print(next(even_gen))
print(’=============’)
for _ in range(50):
print(next(even_gen))

4. Generative-the derivation of the generator

Changing the list comprehension [] into () is the comprehension of the generator, that is, the production

result = (x**2 for x in range(10))
print(result) # <generator object at 0x1018bd5d0>
print(next(result))
print(next(result))
print(next(result))
for item in result:
print(f’item:{item}’)

Module

1. A py file in python is a module.
You can use the content in another module (global variables) in one module, but you need to import the module in advance

2. Import module
1) import module name
a. Import can use all global variables in the specified module;
b. Use variables in the form of'module name. Variable'

2) from module name import variable name 1, variable name 2,...
a. Import the module, you can use the global variables specified in the module;
b. Use the corresponding variable directly, without adding'module name.'

3) Import module name as new module name
Rename the module when importing the module, after renaming, you need to use the imported module through the new module name

  1. from module name import variable as new variable name, …
    rename the specified variable when importing the module

5) (Understand) from module name import *
Import all global variables in the module

Import method 1: import module name
import test1
print(test1.A)
test1.func1()
print(test1.X)

Import method two: from module name import variable
from test1 import A, func1
print(A)
func1()

Import method three: module rename
import test1 as ts1
test1 = 10
test2 = 200
for x in range(test1):
print(x)

Call func1
ts1.func1()
print(ts1.A)
print(ts1.X)

Import method 4: Rename the variable
from test1 import func1 as ts_func1, A, X as ts_X

def func1():
print('func1 in this module')

func1()
ts_func1()
print(A, ts_X)

3. The principle of importing modules
No matter it is through import or from-import, when importing a module, the system will automatically
execute all the codes in the imported module

Note: When importing a module, it has its own duplicate check function (if the imported module has been imported, it will not be imported again)
from test1 import A
print('A:', A)

4. Prevent import When
defining a module, you can use the if statement'if name == " main "' to prevent the specified code in the module from being imported by other modules. (The code in this if statement will not be executed by other modules, and the code not in this if statement will be executed by other modules)

Principle:
By default, there is a variable name in each py file to save the module name of the current module.
When a py file is executed directly, the __name__ in this file will automatically become " main "

import test2
print(‘06:’, name)

Guess you like

Origin blog.csdn.net/xdhmanan/article/details/109088408