Can I make Python throw exception when equal comparing different data types?

后端 未结 3 1277
面向向阳花
面向向阳花 2021-01-18 08:08

Say I want to compare 2 variables with different data types: string and int. I have tested it both in Python 2.7.3 and Python 3.2.3 and neither throws exception. The result

3条回答
  •  借酒劲吻你
    2021-01-18 08:45

    You could define a function to do so:

    def isEqual(a, b):
        if not isinstance(a, type(b)): raise TypeError('a and b must be of same type')
        return a == b # only executed if an error is not raised
    

提交回复
热议问题