用装饰器调用函数

时间:2016-06-04 15:36:16

标签: python python-2.7 python-3.x

我开始在python中学习装饰器。我有以下查询?

def add(a):
  print 'This is an addition function'
  return a


@add
def dollar():
  print 'Am i getting the concept ?'

dollar()

此调用将输出作为

This is an addition function
Am i getting the concept ?

但是如果我这样调用这个函数我会得到以下错误

def add(a):
  a
  print 'This is an addition function'



@add
def dollar():
  print 'Am i getting the concept ?'

dollar()


 This is an addition function
 Traceback (most recent call last):
 File "D:\Python Programs\Sample\src\TestRuns.py", line 10, in <module>
 dollar()
 TypeError: 'NoneType' object is not callable

我的查询是当我们用参数a调用函数时返回它的工作。但是,当我们单独称论证时它不起作用?

2 个答案:

答案 0 :(得分:3)

装饰器必须返回一个在第二个版本中没有的可调用/函数。

def dollar():
    print 'Am i getting the concept ?'
dollar = add(dollar) 

简称:

def add(a):
   a  # this line doesn't do anything!
   print 'This is an addition function'  
   # this line is executed upon decoration

@add  # prints 'This is an addition function'
def dollar():
    print 'Am i getting the concept ?'
# BUT: dollar is now None, since add didn't return anything
# SO:

dollar()

# fails

因此:

dollar

你写第一个版本的装饰者的方式表明你并没有真正得到这个概念。通常会修饰该函数以操纵该函数的行为。你的第一个装饰师根本不会改变print!额外的dollar() dollar() dollar() # Output This is an addition function # decoration Am i getting the concept ? # dollar execution Am i getting the concept ? # dollar execution Am i getting the concept ? # dollar execution 仅在装饰时发生一次,而不是在调用修饰函数时发生:

def add(a):
    def dec_a():
        print 'This is an addition function'
        a()
    return dec_a  # return the augmented function

# Output
This is an addition function  # decoration 
Am i getting the concept ?    # dollar execution
This is an addition function  # decoration 
Am i getting the concept ?    # dollar execution
This is an addition function  # decoration 
Am i getting the concept ?    # dollar execution

如果你希望装饰器将额外的输出行添加到装饰函数的每次调用中,你应该这样做:

import numpy as np
x = np.arange(11)
y = np.arange(11)

X, Y = np.meshgrid(x,y)

答案 1 :(得分:0)

Decorator是一种在执行该方法之前对其他方法进行操作的方法。所以它必须在装饰器函数的末尾返回并返回函数对象。删除return语句将返回None,并阻止执行dollar方法