2

这更像是一个语法错误问题,我正在尝试在 Python Decorators 上完成本教程

http://www.learnpython.org/page/Decorators

我尝试的代码

def Type_Check(correct_type):
    def new_function(old_function):
        def another_newfunction(arg):
            if(isintance(arg, correct_type)):
                return old_function(arg)
            else:
                print "Bad Type"

    #put code here

@Type_Check(int)
def Times2(num):
    return num*2

print Times2(2)
Times2('Not A Number')

@Type_Check(str)
def First_Letter(word):
    return word[0]

print First_Letter('Hello World')
First_Letter(['Not', 'A', 'String'])

我想知道怎么回事,请帮忙

4

1 回答 1

5

看起来您忘记在装饰器末尾返回新定义的函数:

def Type_Check(correct_type):
    def new_function(old_function):
        def another_newfunction(arg):
            if(isinstance(arg, correct_type)):
                return old_function(arg)
            else:
                print "Bad Type"
        return another_newfunction
    return new_function

编辑:还有一些类型,由 andrean 修复

于 2012-10-16T09:26:33.027 回答