Difference between type() and isinstance()

In this article, we will discuss the Difference between type() and isinstance() in Python. The type() and isinstance() are builtin methods in Python. The type() method is used to return the type of particular class. The isinstance() method is used to know to check either the object is below to particular class or not.

type() method:

type() method is a predefined or inbuilt method in Python. It returns the type of the class. theĀ  type() method is defined in two ways

method1:

In this method, we pass a single argument i.e object name. It returns the type of object declared in the method.

The syntax for the type() method is defined below:

type(object_name)

For example:

a=1
type(a)
type([])

Consequently, the output is:

<class 'int'>
<class 'list'>

method2:

In this method, we pass three parameters in the type() method. The first parameter defines the name of the class, the second parameter defines the base class from which it was derived and the third parameter define the dictionary which consists of namespaces used in the class.

The syntax for this type of declaration is:

type(class_name,bases,dictonary)

For example:

class a:
    x='hi'
n=type('n',(a,),dict(x='bye'))
print(type(n))

Consequently, the output is:

<class 'type'>

Similarly, visit type() for more understanding.

isinstance():

isinstance() method is used to find whether the object which was specified in the first argument is a subclass of the class specified in the second argument.

It returns True if the object defined is a subclass of a base class defined otherwise it returns False as an output.

Syntax:

isinstance(object_name,class_name)

For example:

class a:
    pass
x=a()
print(isinstance(x,a))

Consequently, the result is:

True

In the above code can see that ‘x’ is an object created for class ‘a’. In the isinstance() method we declared object ‘x’ as the first parameter and class ‘a’ as the second parameter.

Finally, To know more about isinstance method visitĀ isinstance().

Leave a Reply

Your email address will not be published. Required fields are marked *