【问题标题】:Using Decorators in Python for Type Checking在 Python 中使用装饰器进行类型检查
【发布时间】:2012-10-16 09:20:06
【问题描述】:

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

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'])

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

【问题讨论】:

  • 另外,您的命名选择很差。函数名应该是小写的(见pep-8),像“another_newfunction”这样的名字真的没有意义。

标签: python function decorator


【解决方案1】:

您好像忘记在装饰器末尾返回新定义的函数了:

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 修复

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2016-08-21
    • 2020-08-05
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 2015-06-25
    • 2012-08-07
    • 2019-12-05
    相关资源
    最近更新 更多