noo*_*ker 2 python function decorator
这更像是一个语法错误问题,我正在尝试在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'])
Run Code Online (Sandbox Code Playgroud)
我想知道什么是错的,请帮忙
看起来你忘了在装饰器的末尾返回新定义的函数:
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
Run Code Online (Sandbox Code Playgroud)
编辑:还有一些类型,由andrean修复
| 归档时间: |
|
| 查看次数: |
945 次 |
| 最近记录: |