Algorithm


  1. Purpose:

    • type(): Used to get the type of an object.
    • isinstance(): Used to check if an object is an instance of a particular class or a tuple of classes.
  2. Syntax:

    • type(object): Returns the type of the object.
    • isinstance(object, classinfo): Returns True if the object is an instance of the specified class or a tuple of classes.
  3. Use Cases:

    • type() is primarily used for obtaining the type of an object, e.g., type(5) returns <class 'int'>.
    • isinstance() is used for checking whether an object is an instance of a particular class or any class in a tuple.
  4. Example:

    python
  5. # type() example x = 5 print(type(x)) # Output: <class 'int'> # isinstance() example y = "Hello" print(isinstance(y, str)) # Output: True
  6. Handling Inheritance:

    • type() checks the exact type of the object, while isinstance() considers inheritance. If the object is an instance of a subclass, isinstance() returns True.
  7. Tuple of Classes:

    • isinstance() allows checking against a tuple of classes. If the object is an instance of any class in the tuple, it returns True.
  8. Dynamic Typing:

    • Both functions work well with Python's dynamic typing, allowing flexibility in type checking.
  9. Common Usage:

    • type() is commonly used for basic type checking.
    • isinstance() is preferred when dealing with inheritance and checking against multiple possible types.
  10. Performance:

    • type() is generally faster since it only needs to determine the exact type.
    • isinstance() might be slightly slower due to the additional checks for inheritance.
  11. Conclusion:

    • Use type() for straightforward type checking.
    • Use isinstance() for more flexible type checking, especially when dealing with inheritance or checking against multiple types.

 

Code Examples

#1 Code Example- Difference between type() and instance()

Code - Python Programming

class Polygon:
    def sides_no(self):
        pass

class Triangle(Polygon):
    def area(self):
        pass

obj_polygon = Polygon()
obj_triangle = Triangle()

print(type(obj_triangle) == Triangle)   	# true
print(type(obj_triangle) == Polygon)    	# false

print(isinstance(obj_polygon, Polygon)) 	# true
print(isinstance(obj_triangle, Polygon))	# true
Copy The Code & Try With Live Editor

Output

x
+
cmd
True
False
True
True
Advertisements

Demonstration


Python Program to Differentiate Between type() and isinstance()