标签:lex 添加 font 例子 语法 col return == end
----------------装饰器----------------
用户感觉不到 装饰器的存在
在一个函数前后添加功能
本身的函数不会改变
开放封闭原则
开放 对于扩展是开放的
封闭 对于修改是封闭的
========================装饰器的基本()结构===========================
def wrapper(func):
def inner(*args,**kwargs):
# 被装饰的函数执行之前的操作
ret=func(*args,**kwargs)
# 被装饰的函数执行之后的操作
return ret
return inner
@wrapper
def F(*argument):
pass
-------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------
# import time
# def timmer(F): # 装饰器
# def inner():
# start_time=time.time()
# F()
# end_time=time.time()
# print(end_time-start_time)
# return inner
#
# @timmer # F=timmer(F) # 语法糖
# def F():
# sum=0
# for i in range(1,100000):
# sum+=i # 被装饰的函数
# F() # 直接调用函数,还可以加上装饰器的功能
# -------------------------------------------------------------------------------------------------------
#
# 例子
# import time
#
# def timmer(func):
#
# def inner(*args):
#
# start=time.time()
#
# re=func(*args)
# print(id(func))
#
# end=time.time()
# print(end-start)
#
# return re
#
# print(id(inner))
# return inner
#
#
# @timmer
# def qqxing(num,num2):
# for i in range(1000000):pass
# print(‘Hello‘)
# return num+num2 # 实际函数
#
# ret=qqxing(1,2)
# print(id(qqxing))
# print(ret)
# -------------------------------------------------------------------------------------------------------
# 例子 2
#
# def wrapper(func):
# def inner(*args):
# print(‘你正在调用%s函数‘%(func.__name__))
# re=func(*args)
# return re
# return inner
#
# @wrapper
# def welcome(name):
# print(‘welcome: %s‘%name)
# @wrapper
# def home():
# print(‘欢迎来到home页!!‘)
#
# home()
# print(‘‘)
# welcome(‘alex‘)
# -------------------------------------------------------------------------------------------------
# def wrapper(func):
# def inner(*args,**kwargs):
# #
# re=func(*args,**kwargs)
# #
# return re
# return inner
#
# @wrapper
# def f(a):
# print(a)
# f(1)
# -------------------------------------------------------------------------------------------------
标签:lex 添加 font 例子 语法 col return == end
原文地址:http://www.cnblogs.com/big-handsome-guy/p/7457821.html