Why is it recommended to use Isinstance for type judgment in Python? Rather than type

Source: Internet
Author: User

Transferred from: http://www.xinxingzhao.com/blog/2016/05/23/python-type-vs-isinstance.html

Python does not specify a specific type when defining a variable, and the interpreter automatically checks the type of the variable at run time and implicitly converts the type as needed. Because Python is a dynamic language, type conversions are generally not recommended. For example, "+" operation, if the plus side is the data on both sides of the addition operation, if the two sides is a string string connection operation, if the two sides is a list on the merge operation, even can be complex operation. The interpreter invokes different internal methods at run time, depending on the type of the variable on either side. The TypeError exception is thrown when the variable type is different on both sides of the plus sign, and cannot be converted by type.

However, in the actual development, in order to improve the robustness of the code, we still need to do type checking. The first thing you want to do with type checking is to use type (), such as using type to determine an int type.

TypesType(1types.  IntegerPrint(' 1 is int type ')elseprint(' 1 is not int type ')   

The above program will output: 1 is the int type

We can find some common types in types, the results shown in 2.7.6:

Types.Booleantype# bool TypeTypes.Buffertype# buffer TypeTypes.Builtinfunctiontype# built-in functions such as Len ()Types.Builtinmethodtype# built-in method, refers to a method in a classTypes.ClassType# class TypeTypes.CodeType# code block typeTypes.ComplexType# plural typesTypes.Dictproxytype# Dictionary Proxy typeTypes.Dicttype# dictionary TypeTypes.Dictionarytype# Type of dictionary fallbackTypes.EllipsistypeTypes.FileType# File typesTypes.Floattype# floating-point typesTypes.FrametypeTypes.Functiontype# function typeTypes.GeneratortypeTypes.GetsetdescriptortypeTypes.Instancetype# instance TypeTypes.Inttype# int TypeTypes.Lambdatype# lambda typeTypes.ListType# list TypeTypes.Longtype# Long TypeTypes.MemberdescriptortypeTypes.Methodtype# method TypeTypes.Moduletype# module TypeTypes.Nonetype# none TypeTypes.Notimplementedtypetypes. ObjectType # Object type types. Slicetypehtypes. StringType # String type types. Stringtypes types. Tracebacktype types. Tupletype # tuple type types. Typetype # type itself types. Unboundmethodtypetypes. Unicodetype types. Xrangetype                 

In Python 3, the type has significantly reduced the number of

Types. BuiltinFunctionTypetypes.BuiltinMethodTypetypes.CodeTypetypes.DynamicClassAttributetypes.FrameTypetypes.FunctionTypetypes . GeneratorTypetypes.GetSetDescriptorTypetypes.LambdaTypetypes.MappingProxyTypetypes.MemberDescriptorTypetypes.MethodTypety Pes. ModuleTypetypes.SimpleNamespacetypes.TracebackTypetypes.new_classtypes.prepare_class

However, we do not recommend typing for type checking, and the reason for these types is to extend the knowledge. Then why is it not recommended to use type for typing checks? Let's take a look at the following example.

ImportTypesClassUserint(Int): def __init__ (self val=0): self val = int (val) span class= "n" >i = 1n = userint< Span class= "P" > (2) print (type< Span class= "P" > (i) is type ( span class= "n" >n            

The above code output: False

This means that the type of I and n is not the same, and actually userint is inherited from int, so this judgment is problematic, and when we extend the Python built-in type, the result of type return is not accurate enough. Let's look at one more example.

A():    passbpassA()b()print(type(atype  (b))                

Output of the code: True

The type comparison results in A and B types are the same, and the results are obviously inaccurate. This classical class instance, type returns the same result, and the result is not what we want. For built-in basic types, using Tpye to check is no problem, but when applied to other situations, the type becomes unreliable. At this point we need to use isinstance for type checking.

Isinstance (object, ClassInfo)

object represents an instance, and ClassInfo can be either a direct or indirect class name, a base type, or a tuple with them.

>>> isinstance (2, float) false>>> isinstance (' A ', (str, Unicode)) true>>> isinstance ((2, 3), (str, list, tuple)) True

Why is it recommended to use Isinstance for type judgment in Python? Rather than type

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.