- 首先,要明白python中函数也是个对象,是可以被赋值,可以当做参数传递的。
- 假如我定义一个函数,接收一个函数作为参数,然后调用他,如下:
def mytest(func): return func() def myfunc(): print("Called") mytest(myfunc)
- 如上,会打印出来字符,函数对象传入了mytest,然后在其中调用。
- 再者,函数中可以定义函数,然后返回这个函数对象,如下 is_called中定义了函数,然后返回这个函数,然后new()调用了这个函数,打印出Hello:
def is_called(): def is_returned(): print("Hello") return is_returned new = is_called() new()
- 装饰器就是接收一个函数对象,添加一些语句并返回:
def make_pretty(func): def inner(): print("I got decorated") func() return inner def ordinary(): print("I am ordinary")
上面代码相当于:@make_pretty def ordinary(): print("I am ordinary")
这样,在调用时,则会print(“I got decorated”),再执行原函数中的语句。def ordinary(): print("I am ordinary") ordinary = make_pretty(ordinary)
07-10
07-09
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交