Online Tutorials & Training Materials | STechies.com
Register Login
Advertisement

Difference Between type and isinstance in Python

|| 0

Difference Between type and isinstance in Python
Stechies

type () in Python

type() is a built-in method in python, it is generally is used to know about the type of variable is used in the program, simply we can say that it return type of an object.
Like an argument is passed with type(), as an object, it returns its type.

Example:

Syntax

type(object(s))

With a single argument.

# with a single argument
abc = 5
efg = "string varibale "
xyz = [1,2,3]
print(type(abc))
print(type(efg))
print(type(xyz))

Output:

<type 'int'>
<type 'str'>
<type 'list'>

isinstance() in Python

Using this function you can check for the inheritance, the object is an instance of a class or a base class. The use of isinstance() also can tell you about any of the classes by giving all classes (tuple) rather a single class.

It takes two arguments and returns a Boolean value (true/false).

Syntax

isinstance(object, classinfo)

Object: where an object is checked for an instance of the class or a subclass of a class.
Classinfo : argument checked for a tuple and type of tuple, isinstance () returns true if object is belongs to any type of instance .

The return type is either true, the object is an instance of a class or false if classinfo is not a type of a tuple, or an exception error (typeError) is raised.

Example

# Example of isinstance()
class Isin_ex:
a = 5

TestInstance = Isin_ex()

print(isinstance(TestInstance, Isin_ex))
print(isinstance(TestInstance, (list, tuple)))
print(isinstance(TestInstance, (list, tuple, Isin_ex)))

Output:

True
False
True

 


Advertisement
Advertisement
Advertisement