Home >Backend Development >Python Tutorial >How Can I Determine the Type of an Object in Python?

How Can I Determine the Type of an Object in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-06 16:54:14681browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn