Lanms Blog

python基础-07
Publish: 2019/3/20   

装饰器

def func_3(line):
    def comp(value):
        if value >= line:
            print('{} >= {}'.format(value, line))
        else:
            print('{} < {}'.format(value, line))
    return comp

f = func_3(60)  # 第一次调用外侧函数
f(89)  # 第二次调用内层x
# 相当于 
func_3(60)(89)  
def dec_1(func):
    def wrapper(num1, num2):
        if num2 == 0:
            return ('0000')
        return func(num1, num2)
    return wrapper

def average_1(num1, num2):
    return num1 / num2

# averge_1 = dec_1(average_1)
# a = averge_1(5, 0)
# print(a)
@dec_1
def sum_1(num1, num2):
    return num1 + num2
a = sum_1(1, 0)
print(a)

==接收不同 的参数==

def auth(auth_type):
    def dec_3(func):
        def wrapper(*args, **kwargs):
            if auth_type == '1':
                print('111111111')
            elif auth_type == '2':
                print('22222222')
            else:
                print('0000--0000')
            return func(*args, **kwargs)
        return wrapper
    return dec_3
@auth(auth_type='4')
def average_3(*args):
    return sum(args)
a = average_3(1, 2, 3, 4)
print(a)


← python基础-08 python基础-06 →

Powered by Hexo, Theme designs by @hpcslag.
Style-Framework Tocas-UI designs by @yamioldmel