2
這更是一個語法錯誤問題,我試圖做的Python裝飾本教程在使用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'])
我想知道什麼是錯的,請幫忙
見[類型增強裝飾](http://wiki.python.org/moin/PythonDecoratorLibrary#Type_Enforcement_.28accepts.2Freturns.29) 。 –
另外,你的命名選項很差。函數名應該是小寫的(參見[pep-8](http://www.python.org/dev/peps/pep-0008/)),而像「another_newfunction」這樣的名稱確實沒有意義。 – georg