How to Determine the Type of an Object
Determining the type of an object is crucial for ensuring data consistency and performing operations accordingly. Python provides two built-in functions for this purpose: type() and isinstance().
Using type()
The type() function returns the exact type of an object. For example:
>>> type([]) is list True >>> type({}) is dict True >>> type('') is str True >>> type(0) is int True
Using isinstance()
The isinstance() function checks whether an object is an instance of a particular type, including inherited types. Unlike type(), it supports type inheritance.
>>> isinstance(b, Test1) True >>> isinstance(b, Test2) True >>> isinstance(a, Test1) True >>> isinstance(a, Test2) False >>> isinstance([], list) True >>> isinstance({}, dict) True
Choosing Between type() and isinstance()
Generally, isinstance() is preferred for checking object types as it takes derived types into consideration. Type() is more appropriate if you need the exact type object for specific reasons. Here's an example where you might use isinstance():
def print_object_type(obj): if isinstance(obj, int): print("Integer") elif isinstance(obj, float): print("Float") elif isinstance(obj, str): print("String") else: print("Unknown type")
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3