2012-10-16 74 views
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']) 

我想知道什麼是錯的,請幫忙

+2

見[類型增強裝飾](http://wiki.python.org/moin/PythonDecoratorLibrary#Type_Enforcement_.28accepts.2Freturns.29) 。 –

+3

另外,你的命名選項很差。函數名應該是小寫的(參見[pep-8](http://www.python.org/dev/peps/pep-0008/)),而像「another_newfunction」這樣的名稱確實沒有意義。 – georg

回答

5

看起來你忘了在修飾符的末尾返回新定義的函數:

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

+0

isintance => isinstance – andrean