Home >Backend Development >Python Tutorial >How Can I Determine the Type of an Object in Python?
Determining the Type of an Object
One may find themselves needing to determine the type of a variable, such as whether it's a list or a dictionary. Luckily, there are two built-in functions that aid in this task: type() and isinstance().
type() Function
The type() function returns the exact type of an object. This includes custom types, as demonstrated below:
type([]) # returns 'list' type({}) # returns 'dict' type('') # returns 'str' type(0) # returns 'int'
isinstance() Function
Alternatively, isinstance() allows one to check an object's type against a specified type. It supports inheritance, unlike type().
class Test1(object): pass class Test2(Test1): pass a = Test1() b = Test2() isinstance(b, Test1) # returns True isinstance(b, Test2) # returns True
Furthermore, isinstance() accepts a tuple of types, enabling multiple type checks simultaneously:
isinstance([], (tuple, list, set)) # returns True
Generally, isinstance() is preferred as it verifies type inheritance and allows for multiple type checks.
The above is the detailed content of How Can I Determine the Type of an Object in Python?. For more information, please follow other related articles on the PHP Chinese website!