X Tutup
Skip to content

Latest commit

 

History

History
66 lines (50 loc) · 2.39 KB

File metadata and controls

66 lines (50 loc) · 2.39 KB
title Python isinstance() built-in function - Python Cheatsheet
description Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.
Python isinstance() built-in function From the Python 3 documentation Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof. If object is not an object of the given type, the function always returns False. If classinfo is a tuple of type objects (or recursively, other such tuples) or a Union Type of multiple types, return True if object is an instance of any of the types. If classinfo is not a type or tuple of types and such tuples, a TypeError exception is raised.

Introduction

The isinstance() function checks if an object is an instance of a particular class or a subclass of it. It returns True if the object is of the specified type, and False otherwise.

You can also check against a tuple of types.

Examples

Checking the type of an object:

my_list = [1, 2, 3]
print(isinstance(my_list, list))
print(isinstance(my_list, tuple))
True
False

Checking against multiple types:

print(isinstance("hello", (int, str, list)))
True
isinstance(1, int)
isinstance(1, str)
True
False

Relevant links

  • issubclass()
  • type()
  • OOP Basics
  • Python Data Types
  • callable()
X Tutup