AppDividend
Latest Code Tutorials

Python IsInstance Example | Python isinstance() Function Tutorial

0

Python IsInstance Example | Python isinstance() Function Tutorial is today’s topic. Python isinstance() method returns True if a specified object is of the specified type, otherwise it returns False. If the type parameter is the tuple, this function will return True if the object is one of the types in the tuple. The isinstance() function checks if the object which is the first argument is an instance or subclass of classinfo class which is the second argument.

Python IsInstance Example

The syntax of Python isinstance() method is following.

isinstance(object, type)

The object parameter is required, and it is an object that needs to be checked.

A type or a class, or a tuple of types and classes.

See the following example.

# app.py

class App:
  GoT = 'Aegon'
  
series = App()

print(isinstance(series, App))
print(isinstance(series, (list, tuple)))
print(isinstance(series, (list, tuple, App)))

The output of the above code is following.

Python IsInstance Example

 

Let’s see other examples.

# app.py

numbers = [19, 21, 46]

result = isinstance(numbers, list)
print(numbers,'instance of list?', result)

result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)

result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)

number = 21

result = isinstance(number, list)
print(number,'instance of list?', result)

result = isinstance(number, int)
print(number,'instance of int?', result)

The output is following.

Python IsInstance Tutorial Example

 

Check if “AppDividend” is one of the types described in the type parameter.

# app.py

xyz = isinstance("AppDividend", (float, int, str, list, dict, tuple))
print(xyz)

The output is following.

Python isinstance() Function Tutorial

 

type in Python

Python has a built-in method called a kind which generally comes in handy while figuring out the type of the variable used in the program in the runtime. If a single argument (object) is passed to type() built-in, it returns the type of the given object. If three arguments (name, bases, and dict) are passed, it returns a new type object. See the following example of the type function.

# app.py

a = 10
b = "AppDividend"
c = [19,21,46] 
print(type(a)) 
print(type(b)) 
print(type(c))

The output is following.

type in Python

 

Conclusively, Python IsInstance Example | Python isinstance() Function Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.