Python: 检查函数参数类型
因为我刚从C++转到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??
....
2 个回答
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.")
#.......
4
关于检查类型的必要性,这个话题可能有点开放,但在Python中,遵循“鸭子类型”被认为是一种好习惯。这个函数只会使用它需要的接口,至于调用这个函数的人是否传入正确实现了这些接口的参数,就看他们的选择了。根据这个函数的聪明程度,它可能会具体说明它是如何使用传入参数的接口的。