/  Technology   /  type() and instance()

type() and instance()

What are the differences between type() and instance()?

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.

 

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..

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.

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