美文网首页
12-python中编写无参数decorator

12-python中编写无参数decorator

作者: mingminy | 来源:发表于2017-12-22 09:17 被阅读0次

Python的decorator本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数。

使用 decorator 用Python提供的@语法,这样可以避免手动编写f = decorate(f)这样的代码。

考察一个@log的定义:

def log(f):

def fn(x):

print 'call ' + f.__name__ + '()...'

return f(x)

return fn

对于阶乘函数,@log工作得很好:

@log

def factorial(n):

return reduce(lambda x,y: x*y, range(1, n+1))

print factorial(10)

结果:

call factorial()...

3628800

但是,对于参数不是一个的函数,调用将报错:

@log

def add(x, y):

return x + y

print add(1, 2)

结果:

Traceback (most recent call last):

File "test.py", line 15, in

print add(1,2)

TypeError: fn() takes exactly 1 argument (2 given)

因为add()函数需要传入两个参数,但是@log写死了只含一个参数的返回函数。

要让@log自适应任何参数定义的函数,可以利用Python的*args和**kw,保证任意个数的参数总是能正常调用:

def log(f):

def fn(*args, **kw):

print 'call ' + f.__name__ + '()...'

return f(*args, **kw)

return fn

现在,对于任意函数,@log都能正常工作。

相关文章

  • 12-python中编写无参数decorator

    Python的decorator本质上就是一个高阶函数,它接收一个函数作为参数,然后,返回一个新函数。 使用 de...

  • Python 中修饰器

    修饰器就是一个返回函数的高阶函数 如果decorator本身需要传入参数,那就需要编写一个返回decorator的...

  • 13-python中编写带参数decorator

    考察上一节的@log装饰器: def log(f): def fn(x): print 'call ' + f._...

  • decorater装饰器

    带参数的decorator

  • import decorator

    decorator 是一个帮助你更优雅的编写 decorator 的 decorator 以最常用的 memoiz...

  • 装饰器

    一个完整的decorator的写法如下: 或者针对带参数的decorator:

  • Python中的Decorator: 两种使用场景

    使用 Python 中的Decorator完成以下功能, 代码均是在Python 3.6下编写: 记录函数调用时参...

  • python常用的装饰器

    Python中有很多装饰器(decorator),可以减少冗余代码。Decorator本质上也是函数,只是它的参数...

  • 装饰器

    装饰器 decorator类装饰器 带参数的装饰器 举例(装饰器函数;装饰器类;有参与无参) https://fo...

  • 带参数的decorator

    本文是对浅析decorator一文做的一点补充。国际惯例,先上代码: 执行: 输出: 同没有参数的decorato...

网友评论

      本文标题:12-python中编写无参数decorator

      本文链接:https://www.haomeiwen.com/subject/bpctgxtx.html