python:检查函数的参数类型

问题描述:

由于我刚从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://*.com/questions/378927/what-is-the-best-idiomatic-way-to-check-the-type-of-a-python-变量 – fceruti

那么,作为必要检查类型,这可能是一个有点打开的话题,但在Python中,其认为好的形式遵循"duck typing".该函数只使用它需要的接口,并由调用者来传递(或不)参数那正确实现该接口。根据函数的聪明程度,它可以指定它如何使用它所需参数的接口。

这是事实,在蟒蛇没有必要检查类型的函数的参数,但也许你想要一个这样的效果......

这些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.") 

     #.......