day8(Alex python)

版权声明:本文为博主原创文章,转载请注明作者和出处。https://blog.csdn.net/xq920831/article/details/82349555

有事忙了三天,今天继续更新。

今天主要学习了装饰器。

定义:装饰器本质上是一个函数,功能上是用来装饰其他函数(为其他函数添加附加功能)。

原则:

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

实现装饰器的知识储备:

  • 函数即“变量”
  • 高阶函数
  • 嵌套函数

高阶函数+嵌套函数=>装饰器

==============================================================================

先给一个装饰器的例子:

# -*- coding:utf-8 -*-
# Author: Agent Xu

import time

def timmer(func):
    def warpper(*args,**kwargs):
        start_time = time.time()
        func()
        end_time = time.time()
        print('this fuc used %s seconds' %(end_time-start_time))
    return warpper()

@timmer
def test1():
    time.sleep(3)
    print('this fuc is test1')

test1
#this fuc is test1
#this fuc used 3.0 seconds

===============================================================================

满足下列任意一个条件即可称为高阶函数:

  • 把一个函数名当做一个参数传给另一个函数(在不修改被装饰函数源代码的情况下为其添加功能)
import time

def bar():
    time.sleep(3)
    print('this func is bar')

def test(func):
    start_time = time.time()
    func()
    end_time = time.time()
    print('the func used %s seconds' %(end_time-start_time))

test(bar)
#this func is bar
#the func used 3.0 seconds
  • 返回值中包含函数名(在不修改被装饰函数调用方式的情况下为其添加功能)
import time

def bar():
    time.sleep(3)
    print('this func is bar')

def test2(func):
    print(func)
    return func

test2(bar)
#<function bar at 0x0000000000397F28>   得到bar的内存地址
t = test2(bar)
#<function bar at 0x0000000000397F28>
t() #相当于运行bar()
#this func is bar

#牛逼的来了!!
bar = test2(bar)
#<function bar at 0x0000000000397F28>
bar()   #相当于重新赋值了bar的地址
#this func is bar

嵌套函数(在一个函数里声明另一个函数):

def foo():
    print('this func is foo')
    def bar():   #嵌套在里面的函数相当于局部变量
        print('this func is bar')
    bar()
foo()
#this func is foo
#this func is bar

好!!!!!!!!

明天将会设计一个需求装饰器。

最后附:一个例子看懂全局变量与局部变量

x= 0
def ye():
    x = 1
    def ba():
        x = 2
        def ni():
            x =3
            print(x)
        ni()
    ba()
ye()
#3

猜你喜欢

转载自blog.csdn.net/xq920831/article/details/82349555