1.把一个函数作为另一个函数的参数
注意函数 ly 中传的是另一个函数的地址,而不是对象
import datetime, time def ly(fun): print(datetime.datetime.now()) time.sleep(1) fun() print(datetime.datetime.now()) def work(): print("on working") if __name__ == '__main__': w = work ly(w)
2.在函数内部定义函数
import datetime, time def ly(): print(datetime.datetime.now()) def work(): print("on working") work() time.sleep(1) print(datetime.datetime.now()) if __name__ == '__main__': ly()
注意:仅仅定义是不会执行的,需要手动执行
3.闭包函数(一)
import datetime, time def ly(): info = "on working"; print(datetime.datetime.now()) def work(): print(info) work() time.sleep(1) print(datetime.datetime.now()) if __name__ == '__main__': ly()
有区别吗?
请看闭包函数的定义:
(1).函数内部定义的函数 (2).包含对外部作用域而非全局作用域的引用
注意闭包函数一般返回值,这里只是让读者理解闭包函数
4.闭包函数(二)
import datetime, time def ly(fun): print(datetime.datetime.now()) fun() time.sleep(1) print(datetime.datetime.now()) def work(): info = "on working" def fun(): print(info) return fun if __name__ == '__main__': print("---------------") w = work w() print("---------------") w = work() w() print("---------------") w = work f = w() f() print("---------------")
注意:
(1).第一部分并未任何输出,因为 w 只是 work()函数的一个地址,w() 只返回了 work内部函数fun()函数的地址
(2).第二部分 w 得到的是 work() 函数执行后返回的内部函数fun()的地址,而 w() 便是fun()函数了
(3).第三部分 结合 一二 部分很容易理解
5.装饰器
import datetime, time def ly(fun): def show(): print(datetime.datetime.now()) fun() time.sleep(1) print(datetime.datetime.now()) return show @ly def work(): info = "on working" print(info) if __name__ == '__main__': w = work w()
定义:外部函数传入被装饰函数名,内部函数返回装饰函数名。
特点:(1).不修改被装饰函数的调用方式 (2).不修改被装饰函数的源代码
6.带指定参数的装饰器:
import datetime, time def ly(fun): def show(name): print(datetime.datetime.now()) fun(name) time.sleep(1) print(datetime.datetime.now()) return show @ly def work(name): info = name + " is on working" print(info) if __name__ == '__main__': w = work w("the worker")
注意装饰器替函带参数
7.带不定参数装饰器:
import datetime, time def ly(fun): def show(*args, **kwargs): print(datetime.datetime.now()) fun(*args, **kwargs) time.sleep(1) print(datetime.datetime.now()) return show @ly def work(name, age): info = age + " 岁的 " + name + " is on working" print(info) if __name__ == '__main__': w = work w("ly", "22")
8.多个装饰器
import datetime, time def ly(fun): def show(): time.sleep(1) print("Decorator ly is work on " + str(datetime.datetime.now())) fun() time.sleep(1) print("Decorator ly is work on" + str(datetime.datetime.now())) return show def hh(fun): def show(): time.sleep(1) print("Decorator hh is work on " + str(datetime.datetime.now())) fun() time.sleep(1) print("Decorator hh is work on" + str(datetime.datetime.now())) return show def tx(fun): def show(): time.sleep(1) print("Decorator tx is work on " + str(datetime.datetime.now())) fun() time.sleep(1) print("Decorator tx is work on" + str(datetime.datetime.now())) return show @ly @hh @tx def work(): info = "on working" + str(datetime.datetime.now()) print(info) if __name__ == '__main__': w = work w()
注意:
从中我们可以看出多个装饰器的执行顺序是:
(1).执行函数以前,同装饰器的 装饰先后 顺序
(2).执行函数以后,与装饰器的装饰先后顺序 相反