1、isinstance(param1,param2)
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def confirmType(variate): varType = None if isinstance (variate, str ): varType = "str" elif isinstance (variate,int ): varType = "int" elif isinstance (variate, float ): varType = "float" elif isinstance(variate,tuple): varType = "tuple" elif isinstance (variate, dict ): varType = "dict" elif isinstance (variate, set ): varType = "set" elif isinstance (variate, tuple ): varType = "list" return varType |
2、通过与已知类型的常量进行比较
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | def confirmType(variate): varType= "" if type(variate) == type ('str' ): varType= "str" elif type (variate) = = type ( 1 ): varType= "int" elif type (variate) = = type ( 12.3 ): varType= "float" elif type (variate) = = type ({ "key1" }): varType= "set" elif type (variate) = = type ([ 1 ]): varType= "list" elif type (variate) = = type (()): varType= "tuple" elif type (variate) = = type ({ "key1" : "123" }): varType= "dict" return varType |
补充:
isinstance() 与 type() 区别:
- type() 不会认为子类是一种父类类型,不考虑继承关系。
- isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果判断两个类型是否相同推荐使用 isinstance()。