python零基础学习2-函数1-装饰器

匿名函数:

calc=lambda x:x*3
print(calc(3))      #返回9

 

高阶函数:

  • 可以把一个函数名当做实参传给另一个函数
  • import time
    def bar():
        print("in bar")
    def test(func):
        print(func)
        func()
    
    test(bar)  #执行结果:
    #<function bar at 0x000000C7B80B3E18>     ---bar这个函数的内存地址
    #in bar

     

  • 返回值中可以包含函数名
  • def bar():
        print("in bar")
    
    def test(func):
        print("in test")
        return func
    
    bar=test(bar)
    bar()      #执行结果in test   in bar

     

  • 函数就是变量
  • def bar():
        print("in bar")
    
    test1=bar
    test1()                 #执行结果: in bar

     

嵌套函数

def foo():
    print("in foo")
    def bar():             #有局部变量的特性, 只能在函数内部调用
        print("in bar")
    bar()

foo()     #执行结果:in foo    in bar

 

 

装饰器:

本质是函数, 功能是为其他函数添加附加功能

  • 不能修改被装饰函数的源代码
  • 不能修改被装饰憾事的调用方式

 

装饰器示例1: 统计函数的运行时间

实现原理: 将test这个函数传给timeer, 再将返回值函数赋值给test, 执行test, 即执行wrapper()

弊端: 加了装饰器之后, 返回值会get不到

import time

def timmer(func):
    def wrapper(*args,**kwargs):
        start_time=time.time()
        func()
        stop_time=time.time()
        print("run time:",stop_time-start_time)
    return wrapper

@timmer
def test():
    time.sleep(3)
    print("i am in test")

test()

执行结果:

i am in test
run time: 3.0001983642578125

 

装饰器示例2: 实现登录拦截的功能

def auth(func):    #先将home传给auth, 再将wrapper赋值给home, 执行home, 即执行wrapper
    def wrapper(*args,**kwargs):
        username=input("username:").strip()               #先要求输入用户名密码
        pwd=input("pwd:").strip()

        if username=="alex" and pwd=="123456":           #验证通过打印pass
            print("pass")
            func(*args,**kwargs)
            # res=func(*args,**kwargs)
            # return res
        else:
            exit("验证失败!")                          #验证不通过程序退出
    return wrapper

def index():
    print("欢迎进入登录页!")

@auth
def home(name):
    print("欢迎{name}进入首页!".format(name=name))

index()
home("bell")

 

 装饰器示例3: 装饰器传入参数

def auth(auth_type):   
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            if auth_type=="local":
                user_name=input("username:").strip()
                if user_name=="alex":
                    print("pass")
                    func(*args, **kwargs)
                else:
                    exit()
            elif auth_type=="ldap":
                print("ldap")
                func(*args, **kwargs)
        return wrapper
    return outer_wrapper
@auth(auth_type="local")
def home():
    print("home!")

@auth(auth_type="ldap")
def bbs():
    print("bbs!")

home()
bbs()

 

转载于:https://www.cnblogs.com/bellwang/p/7687982.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值