2011-09-26 121 views
0

由於我剛從C++切換到Python,我覺得python並不太在乎類型安全。例如,任何人都可以向我解釋爲什麼在Python中檢查函數參數的類型是不必要的?python:檢查函數的參數類型

說我定義了一個向量類,如下所示:

class Vector: 
     def __init__(self, *args): 
      # args contains the components of a vector 
      # shouldn't I check if all the elements contained in args are all numbers?? 

現在我想做兩個向量之間的點積,所以我再添功能:

def dot(self,other): 
    # shouldn't I check the two vectors have the same dimension first?? 
    .... 
+0

這裏是如何做到這一點的答案http://stackoverflow.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-變量 – fceruti

回答

4

那麼,作爲必要檢查類型,這可能是一個有點打開的話題,但在Python中,其認爲好的形式遵循"duck typing".該函數只使用它需要的接口,並由調用者來傳遞(或不)參數那正確實現該接口。根據函數的聰明程度,它可以指定它如何使用它所需參數的接口。

1

這是事實,在蟒蛇沒有必要檢查類型的函數的參數,但也許你想要一個這樣的效果......

這些raise Exception在運行期間發生......

class Vector: 

    def __init__(self, *args):  

     #if all the elements contained in args are all numbers 
     wrong_indexes = [] 
     for i, component in enumerate(args): 
      if not isinstance(component, int): 
       wrong_indexes += [i] 

     if wrong_indexes: 
      error = '\nCheck Types:' 
      for index in wrong_indexes: 
       error += ("\nThe component %d not is int type." % (index+1)) 
      raise Exception(error) 

     self.components = args 

     #...... 


    def dot(self, other): 
     #the two vectors have the same dimension?? 
     if len(other.components) != len(self.components): 
      raise Exception("The vectors dont have the same dimension.") 

     #.......