Using Decorators in Python for Type Checking

江枫思渺然 提交于 2020-01-02 17:36:31

问题


This is more of a syntax error issue, I am trying to do this tutorial on Python Decorators

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

My Attempted Code

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

I am wondering whats wrong, please help


回答1:


It looks like you forgot to return the newly defined function at the end of the decorator :

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

EDIT : there was also some types, fixed by andrean



来源:https://stackoverflow.com/questions/12911395/using-decorators-in-python-for-type-checking

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