##### Python learning (seven) #####

### how to quickly generate codes (code interpolation) ###
codes (code interpolation) generally consist of uppercase and lowercase letters or numbers
import random # adding random modules
additional character module import string #

str = string.ascii_letters + string.digits  ##所有大小写字母和数字
str =  string.digits   ##所有数字
str1 = string.ascii_lowercase    ##所有小写字母
 str2 = string.ascii_uppercase  ##所有大写字母

code_str = string.ascii_letters + string.digits
# code_str1 = string.ascii_lowercase
# code_str2 = string.ascii_uppercase
# print(code_str1)
# print(code_str2)
print(code_str)

# print(random.sample(code_str,4))
def gen_code(len=4):
    #     code = ''
    #     for i in range(len):
    #         new_s = random.choice(code_str)
    #         code += new_s
    #
    #     return code
    return ''.join(random.sample(code_str, len))
# print(gen_code())
print([gen_code() for i in range(1000)])

The random.choice (list) # randomly select one from the list
random.sample (list number) # specified number of randomly selected in the list
generated 100 8-digit code

方式一
import random
import string

def passwd( ):
    str = string.ascii_letters + string.digits
    s = ''.join([random.choice(str)for i in range(8)])
    return s
result = [passwd() for t in range(100)]
print(result)
方法二:
import random
import string
str1 = string.ascii_letters + string.digits
result1 = [''.join(random.sample(str1,8))for i in range(100)]
print(result1)

#### decorator ###
becomes transparent when the python program can decorator to different functions into the same functionality as compared to other high-level languages simplifies decorative python code function also as a function of increasing
decorator:
the concept: to a function as a parameter to a function, the function returns an alternative version
is essentially a function that returns a function
"without changing the original function, add functionality to the function"
create a decorator:
a decorator is simply a function, only the parameters decorator function must be a function, then the decorator function to redefine a new function, and perform certain functions or around the middle of the decorator in which the final return the newly defined function

def outer(fun):
     def inner():
         print('第一层装饰器:原函数执行前打印语句')
         fun()
         print('第一层装饰器:原函数执行后打印语句')
     return inner

def original_fun():
     print('原函数内容')
original_fun()
original_fun = outer(original_fun)
original_fun()
运行
原函数内容
第一层装饰器:原函数执行前打印语句
原函数内容
第一层装饰器:原函数执行后打印语句

Syntactic sugar decorator
before you can use the "@" to achieve, using the @ + decorate its name in the function definition line

def outer(fun):
     def inner():
         print('第一层装饰器:原函数执行前打印语句')
         fun()
         print('第一层装饰器:原函数执行后打印语句')
     return inner
@outer
def original_fun():
     print('原函数内容')
original_fun()
运行
第一层装饰器:原函数执行前打印语句
原函数内容
第一层装饰器:原函数执行后打印语句

Decorator implement a timer function

import time   #调入时间模块
import string
import random
import functools

li = [random.choice(string.ascii_letters)
      for i in range(1000)]
def timeit(fun):
    # 问题1:被装饰的函数有返回值的时候怎么办?
    # 问题2:被装饰的函数如何保留自己的函数名和帮助信息文档?
    @functools.wraps(fun)
    def wapper(*args, **kwargs):
        """这是一个wapper函数"""
        # 在函数的执行之前
        start_time = time.time()
        # 执行函数
        res = fun(*args, **kwargs)
        # 在函数执行之后
        end_time = time.time()
        print('运行的时间为:%.6f' % (end_time - start_time))
        return res
    return wapper


@timeit
def con_add():
    s = ''
    for i in li:
        s += (i + '+')
    print(s)


@timeit
def join_add():
    print('+'.join(li))

con_add()
join_add()

 @timeit
 def fun_list(n):
 """这是fun_list函数,被timeit装饰"""
    return [2 * i for i in range(n)]
 @timeit
def fun_map(n):
    """这是fun_map函数,被timeit装饰"""
 return list(map(lambda x:x*2,range(n)))

 #fun_list(5000)
 fun_map(5000)
 print(fun_list.__doc__)
print(fun_map.__doc__)
 print(fun_list.__name__)
  print(fun_map.__name__)

Multiple decorators

"""
def decorator_a(fun):
    def inner_a(*args,**kwargs):
        print('Get in inner_a')
        return fun(*args,**kwargs)
    return inner_a

def decorator_b(fun):
    def inner_b(*args,**kwargs):
        print('Get in inner_b')
        return fun(*args,**kwargs)
    return inner_b

##多个装饰器装饰函数,从上到下执行
@decorator_b
@decorator_a
def f(x):
    print('Gat in f')
    return x*2

f(1)

Decorator with parameters

import functools
import time

def log(kind):
    def add_log(func):
        @functools.wraps(func)
        def wrapper(*args,**kwargs):
            start_time = time.time()
            res = func(*args,**kwargs)
            end_time = time.time()
            print('<%s>[%s] 函数名:%s,运行时间:%.6f,运行返回值的'
              '结果:%d' %(kind,time.ctime(),func.__name__,
                        end_time-start_time,res))
            return res
        return wrapper
    return add_log
@log('debug')
def add(x,y):
    time.sleep(1)
    return x+y
print(add(1,2))

When there is a parameter of the function to be decorated
when the decorator constructed as a function return value is used in place of a function as a parameter, so that these two functions must be consistent with the parameters. In the definition of decorator when specified function parameter may have any number of parameters and functions as a return value can have any number of parameters, so that even when the decorator convenient

def store(func):#定义一个函数,参数也是函数
    def inner_f(*args,**kwargs):#指定返回的函数可以有任意个参数
        """这是装饰器store的函数"""
        print('welcome!!!')
        func(*args,**kwargs)
    return inner_f  #返回值是另一个函数

@store
def thing1(name):  #装饰一个参数的函数
    print('%s is frute' %name)
@store
def thing2(name,price): #装饰两个参数的函数
    print('%s is frute ,price is %d' %(name,price))

thing1('apple')
thing2('apple',10)
输出:
welcome!!!
apple is frute
welcome!!!
apple is frute ,price is 10

2. decorative function returns a value
required as a function of the value returned in the return value as a parameter in the function accepts decoration decorator, returned back after

def store(func):#定义一个函数,参数也是函数
    def inner_f(*args,**kwargs):#指定返回的函数可以有任意个参数
        """这是装饰器store的函数"""
        print('welcome!!!')
        res = func(*args,**kwargs)  #使用变量接受返回值
        return res  #将变量接受的返回值再次返回
    return inner_f

@store
def thing1(name):
    print('%s is frute' %name)
@store
def thing2(name,price):
    print('%s is frute ,price is %d' %(name,price))

thing1('apple')
thing2('apple',10)

3. garnished retain their function and function names help document information
when the function is decorative, decorator will return to perform new functions instead of the original function, then the function name and function of the document will become a decorator function defined in

def store(func):#定义一个函数,参数也是函数
    def inner_f(*args,**kwargs):#指定返回的函数可以有任意个参数
        """这是装饰器store的函数"""
        print('welcome!!!')
        res = func(*args,**kwargs)  #使用变量接受返回值
        return res  #将变量接受的返回值再次返回
    return inner_f

@store #使用装饰器装饰
def frutes1(name):
    """这是被装饰frute的函数"""
    print('%s is frute' %name)

@store
def frutes2(name,price):
    return ('%s is frute ,price is %d' %(name,price))

print(frutes1.__doc__)  #输出函数文档
print(frutes2.__doc__)
print(frutes1.__name__)#输出函数名称
print(frutes2.__name__)

Python provides functools.wraps, allows us to function attributes before the visit of Lee decorator
must first call: import functolls

import functools

def store(func):#定义一个函数,参数也是函数
    @functools.wraps(func)  ##使用该函数保留原函数的名称和文档等属性
    def inner_f(*args,**kwargs):#指定返回的函数可以有任意个参数
        """这是装饰器store的函数"""
        print('welcome!!!')
        res = func(*args,**kwargs)  #使用变量接受返回值
        return res  #将变量接受的返回值再次返回
    return inner_f

@store #使用装饰器装饰
def frutes1(name):
    """这是被装饰frute1的函数"""
    return ('%s is frute' %name)

@store
def frutes2(name,price):
    """这是被装饰frute2的函数"""
    return ('%s is frute ,price is %d' %(name,price))

print(frutes1.__doc__)  #输出函数文档
print(frutes1.__name__)  #输出函数名称
print(frutes2.__doc__)
print(frutes2.__name__)
运行:
这是被装饰frute1的函数
frutes1
这是被装饰frute2的函数
frutes2   #原函数的内容

A plurality of decorator simultaneously a decorative function, performed from top to bottom

import functools

def store(func):#第一个装饰器
     @functools.wraps(func)
     def inner_f(*args,**kwargs):
         print('welcome!!!')
         res = func(*args,**kwargs)
         return res
     return inner_f


def goods(func):#第二个装饰器
    @functools.wraps(func)
    def inner_f(*args, **kwargs):
        print('Hello!!!')
        res = func(*args, **kwargs)
        return res
    return inner_f
@goods
@store
def frutes1(name,price):
    print('%s is frute ,price is %d' %(name,price))
frutes1('apple',13)
运行:
Hello!!!
welcome!!!
apple is frute ,price is 13

Decorators with arguments
decorator is a function by function name (parameter) can be called, then the function returns the name after the @ function call parameters passed in the outermost

import functools
def welcome(time):
  def store(func):
     @functools.wraps(func)
     def inner_f(*args,**kwargs):
         print(time)
         print('welcome!!!')
         res = func(*args,**kwargs)
         return res
     return inner_f
  return store

@welcome(20190603)
def frutes1(name,price):
    print('%s is frute ,price is %d' %(name,price))
frutes1('apple',13)

Guess you like

Origin blog.csdn.net/weixin_44821839/article/details/90738412