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
Release: 2024-12-06 16:54:14
Original
688 people have browsed it

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'
Copy after login

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
Copy after login

Furthermore, isinstance() accepts a tuple of types, enabling multiple type checks simultaneously:

isinstance([], (tuple, list, set))  # returns True
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template