Decorator for Python study notes

content


decorator

Add new functions to the function without changing the function code, and the calling method does not need to be changed

The derivation process

Add functions to the method without changing the method source code and calling method. The code is as follows:

def timer(func):
    def decorator(*args,**kwargs):
        start_time=time.time()
        func(*args,**kwargs)
        end_time=time.time()
        print('spend time : %s' %(end_time-start_time))
    return decorator


def func1():
    time.sleep(1)
    print('in the func1')


func1=timer(func1)
func1()

Simple decorator example:

Add running time timing function to the function, and the function has formal parameters

def timer(func):
    def decorator(*args,**kwargs):      #内嵌函数,也就是装饰器,参数个数无限制
        start_time=time.time()
        func(*args,**kwargs)
        end_time=time.time()
        print('spend time : %s' %(end_time-start_time))
    return decorator                    #把装饰器内存地址返回

@timer                          #把内存地址复制给func1,也就是函数本身,所以执行的代码块是刚刚定义的装饰器,原理和上面推导过程一样
def func1(name,age):            #有参数的函数
    time.sleep(1)
    print('in the func1,name is {_name} and age is {_age}'.format(_name=name,_age=age))


@timer
def func2():                    #无参数的函数
    time.sleep(1)
    print('in the func2')


func1("domain",18)            #再调用时就是执行装饰器的代码
func2()

Examples of complex decorators:

The decorator passes in parameters, and the decorated function has a return value

user,password='domain','123'

def auth(type):                         
    print("type",type)
    def out(func):
        def decor(*args,**kwargs):
            if type=="1":
                username=input('please input your name')
                userpassword=input('please input your password')
                if user==username and password==userpassword:
                    print('passed auth')
                    res=func()
                    return res
                else:
                    print('you username or password invaild.')
            elif type=="2":
                print("type ==2 ")
                username = input('please input your name')
                userpassword = input('please input your password')
                if user == username and password == userpassword:
                    print('passed auth')
                    res = func()
                    return res
                else:
                    print('you username or password invaild.')
        return decor
    return out


def index():
    print("welcome to index")

@auth("1")
def home():
    print("welcome to home")
    return "result form home "

@auth("2")
def bbs():
    print("welcome to bbs")

index()
print(home())
bbs()

Builder

Generate while looping, infer the element data through an algorithm, and become a generator


Features

  1. The corresponding data will only be generated when the call is made
  2. Only record the current location
  3. only one next method

Simple Generator - List Compilation

Turn the list into a generator

c=(i*2 for i  in range(10))
print(c)                        //为生成器 地址:<generator object <genexpr> at 0x000000BAAC687990>
print(c.__next__())             //为生成器里面的第一个值

complex generator-function

#斐波那契
def fib(max):
    n,a,b=0,0,1
    while n<max:
        # print(b)
        yield b                 #定义b为 生成器的值 一碰到yield函数退出
        a,b=b,a+b
        n=n+1
    return 'done'                  #生成器异常返回值

c=fib(10)
print(c.__next__())

while True:
    try:
        print(c.__next__())
    except StopIteration as e:          #捕获超出生成器大小异常
        print("exception:",e.value)
        break

The send method sends data to the generator

def consumer (name):
    print("%s准备吃包子啦!"%name)
    while True:
        baozi=yield
        print("包子[%s]来了,被[%s]吃了!"%(baozi,name))

c=consumer("domain")
c.__next__()            #第一次执行 碰到yield 结束
c.send("韭菜馅")        #发送数据给生成器第二次执行 输出语句,然后进入循环 碰到yield 结束

iterator

  • Iterative objects: Objects that can be used in for loops become iterative objects (Iteralbe), such as: list, tuple, dict, set, str, and generators.
  • Iterator: An object that can be called by the next function and continuously returns the next value becomes an iterator (Iterator)

basic function

  • Whether it is an iterative object (use the isinstance function to interpret after importing the module):
from collections import  Iterable,Iterator
print(isinstance([],Iterable))
print(isinstance((),Iterable))
print(isinstance({"name","domain"},Iterable))
print(isinstance("domain",Iterable))
print(isinstance(123,Iterable))
  • Whether it is an iterator (use the isinstance function to interpret after importing the module):
from collections import  Iterable,Iterator
print(isinstance([],Iterator))
print(isinstance((),Iterator))
print(isinstance({"name","domain"},Iterator))
print(isinstance("domain",Iterator))
print(isinstance(123,Iterator))
  • To turn non-iterators (iterable objects) into iterators, use the iter function:
a=[1,2,3]
b=iter(a)   
b.__next__()

expand

  • The for loop is also implemented with iterators:
for x in range(10):
    print(x)


        break

Equivalent to:

it = iter([0,1,2,3,4,5,6,7,8,9])
while True:
    try:
        x=it.__next__()
        print(x)
    except:
        break
  • The reading of files is also achieved through iterators:
for f in f:
    print(f)

For more latest Python tutorial resources, follow the WeChat public account Caesars Network Research Institute , and reply to Python to get it.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326312851&siteId=291194637