Decorated function returns None

落爺英雄遲暮 提交于 2019-12-31 03:04:58

问题


I have a decorator that checks a function's argument for int type.

def check_type_int(old_function):
    def new_function(arg):
        if not isinstance(arg, int):
            print 'Bad Type'    # raise TypeError('Bad Type')
        else:
            old_function(arg)
    return new_function

When I run a decorated function, it returns None instead of an int value.

@check_type_int
def times2(num):
    return num*2

times2('Not A Number')  # prints "Bad Type"
print times2(2)         # prints "None"

The last line should print 4. Can someone please spot my mistake? Thanks.


回答1:


You don't return any value from new_function inside the decorator, therefore it returns None by default. Just change this line:

old_function(arg)

to

return old_function(arg)



回答2:


Adding to the answer by @eugeney: it would be easier if you used return for both cases in if:

if not isinstance(arg, int):
    return 'Bad Type'          # return 
else:
    return old_function(arg)   # return

And this:

print times2('2')                # prints Bad Type
print times2(2)                  # prints 4



回答3:


You need to use *args and **kwargs

def dec(function):
    def new_f(*args, **kwargs):
        return function(*args, **kwargs)
    return new_f


来源:https://stackoverflow.com/questions/37907505/decorated-function-returns-none

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!