【问题标题】:python: check function parameter typespython:检查函数参数类型
【发布时间】:2011-11-24 20:55:12
【问题描述】:

由于我刚从 C++ 切换到 Python,感觉 Python 不太关心类型安全。例如,谁能向我解释为什么在 Python 中不需要检查函数参数的类型?

假设我定义了一个 Vector 类如下:

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??
     ....

【问题讨论】:

标签: python


【解决方案1】:

在python中确实不需要检查函数参数的类型,但也许你想要这样的效果......

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

        #.......

【讨论】:

    【解决方案2】:

    好吧,至于检查类型的必要性,这可能是一个有点开放的话题,但在python中,它被认为是遵循"duck typing".的好形式@该函数只是使用它的接口需要,并且由调用者传递(或不传递)正确实现该接口的参数。根据函数的聪明程度,它可能会指定它如何使用它所接受的参数的接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      相关资源
      最近更新 更多