开发者

python: check function parameter types

Since I just switched to Python from C++, I feel like python does not care much about type safety. For example, can anyone explain to me why checking the types of function parameters is not necessary in Python?

Say I defined a Vector class as follows:

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

And now I want to do dot product between two vectors, so I add another function:

def dot(self,other):
     # shouldn't I check the t开发者_C百科wo vectors have the same dimension first??
     ....


Well, as for necessity of checking the types, that may be a topic that's a bit open, but in python, its considered good form to follow "duck typing". The function just uses the interfaces it needs, and it's up to the caller to pass (or not) arguments that properly implement that interface. Depending on just how clever the function is, it may specify just how it uses the interfaces of the arguments it takes.


It is true that in python there is no need to check the types of the parameters of a function, but maybe you wanted an effect like this...

These raise Exception occur at runtime...

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

        #.......
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜