python3进阶高级_Python3高级-装饰器,进阶

1.装饰器功能:

在不修改原函数的情况下,增强函数功能

2.不带参数的函数+不带参数的装饰器

(1)foo()被装饰的函数

(2)show_time() 是装饰器

# -*- coding:utf-8 -*-

import time

def show_time(func):

def inner():

start_time = time.time()

func()

end_time = time.time()

print("执行时间为:", end_time - start_time)

return inner

@show_time

def foo():

print("我是foo函数")

time.sleep(1)

foo()

3.带参数的函数+不带参数的装饰器

# -*- coding:utf-8 -*-

import time

def show_time(func):

def inner(*args, **kwargs):

start_time = time.time()

func(*args, **kwargs)

end_time = time.time()

print("执行时间为:", end_time - start_time)

return inner

@show_time

def foo(something):

print("我在:", something)

time.sleep(1)

foo("看电视")

4.带参数的函数+带参数的装饰器

# -*- coding:utf-8 -*-

# -*- coding:utf-8 -*-

import time

def wrapper(name):

def show_time(func):

def inner(*args, **kwargs):

start_time = time.time()

func(*args, **kwargs)

end_time = time.time()

print(name)

print("执行时间为:", end_time - start_time)

return inner

return show_time

@wrapper("test") # wrapper("test")(foo)("看电视")

def foo(something):

print("我在:", something)

time.sleep(1)

foo("看电视")

附加的解释:

1.函数:

(1)函数名可以作为参数

(2)函数名可以作为返回值

(3)函数名可以赋值

2.闭包:函数内部的函数,对嵌套作用域的变量进行引用,那么这个内部函数被称为闭包(inner函数就是闭包)

你可能感兴趣的:(python3进阶高级)