问题
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