/  Technology   /  Type() and instance() in Python

Type() and instance() in Python

 

The isinstance() function checks if the object(first argument) is an instance or subclass of classinfo class (second argument).

 

isinstance(object, class info)

  •   ‘object’ whose type is to be checked.
  •   ‘classinfo’ contains class, type, or a tuple of classes and types.

 

This function returns True if the object is an instance or a subclass of a class or an element belonging to the tuple. It returns False otherwise.

 

If classinfo is not a type or a tuple of types, an exception named TypeError is raised.

 

Example:

class color:
   a = 'blue'

colorinstance = color()

print(isinstance, color))
print(isinstance, (list, tuple)))
print(isinstance, (list, tuple, color)))

Output:

 

The type() function on the other hand has two different forms:

  •       type(object)
  •       type(name, bases, dict)

 

In the first form, type() has a single object parameter, i.e., a single object is passed to type() and the function returns its type.

Example:

colors = ['red', 'blue']
print(type(colors))

colors_dict = {1: 'red1', 2: 'blue2'}
print(type(colors_dict))

class A:
   p = 0

a = A()
print(type(A))

Output:

 

In the second form, type() with name, bases and dict parameters, three parameters are passed to type() and it returns a new type object.

  •  name: a class name makes this.
  •  bases: a tuple that particularizes the base class.
  •  dict: a dictionary that contains definitions for the class body.

 

Example:

x1 = type('P', (colors,), dict(a='Red', b=12))

print(type(x1))

class number:
   a = 'Red'
   b = 12

x2 = type('Q', (number,), dict(a='Red', b=12))
print(type(x2))

Output:

 

One primary mistake which people commit is using the type() function where isinstance() would be more appropriate.If our need is to check if an object is of a certain type, we would need an isinstance() function, as it checks if the object, the first argument belongs to any of the type objects passed in the second argument.

 

On the other hand, type() simply returns the type object of an object, and comparing the returned value to another type object will return True when we use the exact same type object on both sides.

 

Leave a comment