Вопрос

I've been experimenting decorator in python 2.7 and tried setup in idle:

def logme(func):
    def wrapped(*args):
        for arg in args: print str(arg)
        func(*args)
    return wrapped

@logme
def my_func(*args):
    res = 1
    for arg in args :
        print "Multiplying %s by %s" % (arg, res)
        res*=arg
    print res
    return res

The output is this:

2
3 
Multiplying 2 by 1
Multiplying 3 by 2
6

So the res value is right. However, when I tried to store the res value via this:

x = my_func(2,3)

The value of x is None. Is this correct? If not, what am I doing wrong here?

Это было полезно?

Решение

You forgot to return the result of func() in your wrapper:

def logme(func):
    def wrapped(*args):
        for arg in args: print str(arg)
        return func(*args)
    return wrapped

otherwise wrapped() calls func() but ignores the returned result.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top