码迷,mamicode.com
首页 > 其他好文 > 详细

装饰器

时间:2019-08-21 21:55:54      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:**kwargs   imp   开放封闭原则   inner   功能   时间戳   tar   主页   port   

装饰器:

开放封闭原则:

1。代码扩展进行开放

2。修改源代码是封闭的

在不修改源代码及调用方式,对功能进行额外添加就是封闭原则

def index ():

print("这是个主页")

index()

修饰(额外功能) 器:工具(函数)

import time

def func():

time.sleep(1)

print("这是小刚写的功能")

def index():

time.sleep(2)

print("这是小刚写的功能")

def red():

time.sleep(3)

print("这是小红写的功能")

start_time = time.time()

index()

print(time.time() - start_time)

start_time = time.time()

func()

print(time.time() - start_time)

start_time = time.time()

red()

print(time.time() - start_time)

import time

def index():

time.sleep(2)

print("这是小明写的功能")

def func():

time.sleep(3)

print("这是李虎写的功能")

def red():

time.sleep(4)

print(‘这是建伟写的功能‘)

def times(func):

start_time = time.time()

func()

print(time.time()-start_time)

times(index)

times(func)

times(red)

import time

def index():

time.sleep(3)

print("建伟完事了")

def func():

time.sleep(1)

print("李虎完事了")

def red():

time.sleep(2)

print("种猪完事了")

def times(func):

start_time = time.time() # 时间戳

func()

print(time.time() - start_time)

f = index

index = times

index(f)

f1 = func

func = times

func(f1)

f2 = red

red = times

red(f2)

第一版装饰器

import time

def func():

time.sleep(1)

print("陈冠希完事了")

def red():

time.sleep(1)

print("王强完事了")

def index():

time.sleep(2)

print("胡斌完事了")

def times (func):

def foo ():

start_time =time.time()

func ()

print(time.time() - start_time)

return foo

index = times(index)

index()

func = times(func)

func()

red = times(red)

red()

def func():

print("被装饰的函数")

def warpper(f):

def inner():

print("111")

f()

print("222")

return inner

func = warpper(func)

func()

def warpper(f):

def inner():

print("111")

f()

print("222")

return inner

@warpper # func = warpper(func)

def func():

print("被装饰的函数1")

@warpper # index = warpper(index)

def index():

print("被装饰的函数2")

func()

def warpper(f):

def inner():

print("111")

f()

print("222")

return inner

@warpper # func = warpper(func)

def func():

print("被装饰的函数1")

@warpper # index = warpper(index)

def index():

print("被装饰的函数2")

# python帮咱们做的一个东西,语法糖

func()

index()

def warpper(f):

def inner(*args,**kwargs):

print("被装饰函数执行前")

ret = f(*args,**kwargs)

print("被装饰函数执行后")

return ret

return inner

@warpper#func = warpper(func)

def func(*args,**kwargs):

print(f"被装饰的{args,kwargs}")

return "我是func函数"

# func(1,2,3,4,5,6,7,8,a=1)

print(func(1,2,3,4,5,6,7,8,a=1))

@warpper

def index(*args,**kwargs):

print(11111)

index()

装饰器

标签:**kwargs   imp   开放封闭原则   inner   功能   时间戳   tar   主页   port   

原文地址:https://www.cnblogs.com/x-h-15029451788/p/11391152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!