装饰函数返回None

时间:2016-06-19 13:00:18

标签: python python-decorators

我有一个装饰器,用于检查int类型的函数参数。

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

当我运行一个修饰函数时,它返回None而不是int值。

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

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

最后一行应打印4。有人可以发现我的错误吗?感谢。

3 个答案:

答案 0 :(得分:2)

您不必return来自装饰器内new_function的任何值,因此默认情况下会返回None。只需更改此行:

old_function(arg)

return old_function(arg)

答案 1 :(得分:0)

通过@eugeney添加到answer:如果您在print times2('2') # prints Bad Type print times2(2) # prints 4 中使用int main() { introduction(); int x; cin >> x; if (x == 1) cout << endl << "1. Only state true information." << endl << "2. Do not copy this servey and distribute it AT ALL." << endl << "3. Do not falsely advertise this survey anywhere." << endl << endl; cout << "(Press 1 to start survey)" << endl; int y; cin >> y; if (y == 1) int gender = askGender(); int job = askJobOrNot(); int sport = askFavSport(); int music = askFavMusicGenre(); int birth = askBirthPlace(); int colour = askFavColour(); cout << endl << "Thank you, you have successfully completed the survey! (: " << endl; cout << "(Press 1 to show results, and press 2 to quit)" << endl; int s; cin >> s; if (s == 1) printResults(gender, job, sport, music, birth, colour); if (s == 2) quitProgram(); return 0; } 这两种情况会更容易:

TOP(1) WITH TIES

而且:

ORDER BY Weight DESC

答案 2 :(得分:-1)

你需要使用* args和** kwargs

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