1、检视一个函数相同的另外一种方法python
利用属性:函数._namegit
def hello(): print("我是一个测试程序") f = hello print(f.__name__) print(hello.__name__)
从结果来看他们的本体都是hello函数github
2、装饰器微信
1.定义:在不改动代码的基础上无限扩展函数功能的一种机制,本质上来说,装饰器是一个返回函数的高阶函数。app
2.装饰器的使用:使用@愈发,即在每次要扩展到函数定义前使用@+函数名。函数
import time #对hello函数进行功能扩展,每次执行hello前打印时间 def printTime(f): # 高阶函数,以函数做为参数 def wrapper(*args,**kwargs): print("Time:",time.ctime()) return f(*args,**kwargs) return wrapper #上面定义了装饰器,使用的时候须要用到@符号,此符号是python语法 @printTime def hello(): print("Hello World") hello()
3.装饰器的好处:学习
(1)装饰器的好处是,一旦定义,则能够装饰任意函数
(2)一旦被其装饰,则把装饰器的功能直接添加在定义函数的功能上测试
4.上面对函数的装饰使用了系统定义的语法糖,下面开始手动执行一下装饰器大数据
.......复用了上面的代码........ def hello3(): print("厉害") hello3 = printTime(hello3) #这是向printTime传参hello3,而后返回wrapper,也就是hello3 = wrapper hello3() #执行了hello3函数,也就是执行了wrapper函数,先打印了“厉害”而后返回了最开始的hello3,可是后面有括号就是执行了最开始的 #hello3(),打印了厉害
5.遗留问题:ui
aa = printTime(hello3)
aa()
为何出来了两个时间戳
3、源码:
d20_3_wrapper
地址:https://github.com/ruigege66/Python_learning/blob/master/d20_3_wrapper
2.CSDN:https://blog.csdn.net/weixin_44630050(心悦君兮君不知-睿)
3.博客园:https://www.cnblogs.com/ruigege0000/
4.欢迎关注微信公众号:傅里叶变换,后台回复”礼包“,获取大数据学习资料