Quantcast
Channel: Linux Guides, Tips and Tutorials | LinuxScrew
Viewing all articles
Browse latest Browse all 314

Python isinstance Function, With Example [Guide]

$
0
0

The Python isinstance() function determines the type or class of a variable. Read on to find out exactly how isinstance works, with an example below.

What are Types?

The type of a variable determines what it can or can’t do.

It determines what value the variable may take and what can be done with that value.

isinstance Syntax

isinstance(OBJECT, CLASS)

Note that:

  • OBJECT is the variable or value to check the type or class of
  • CLASS is the type or class we want to see if the variable type matches
  • The function returns a boolean value (True/False)

Types in Python

Generally, the type of a variable is assigned automatically when a value is assigned to it, based on the value.

It is also possible to explicitly set the type if it is different from what would be expected.

Python has several built-in types – stringsintegers, and lists among them.

You can also define your own classes for your own variable structures and test against them.

isinstance Examples

Checking the Type of a Variable

The below example sets several variables, prints their type, then checks their type:

var1 = 3
var2 = "LinuxScrew!"
var3= ["red", "green", "blue"]
var4 = False

print(type(var1)) # Will output that the type is int
print(type(var2)) # Will output that the type is str
print(type(var3)) # Will output that the type is list
print(type(var4)) # Will output that the type is bool

print(isinstance(var1, int)) # True
print(isinstance(var2, bool)) # False
print(isinstance(var3, list)) # True
print(isinstance(var4, bool)) # True

Checking the Type of a Custom Class

Python allows you to define custom classes for your variables, which you can also check:

# Define a custom variable class which describes a car
# Values given are defaults for the class
class carClass:
    make = "Ford"
    model = "Falcon"

var = carClass()

print(isinstance(var, carClass)) # Will return True

 

View the original article from LinuxScrew here: Python isinstance Function, With Example [Guide]


Viewing all articles
Browse latest Browse all 314

Trending Articles