Python’s type() Function

Learn Python @ Freshers.in

In Python, the type() function is a versatile tool for dynamic type checking and object creation. This article aims to provide a comprehensive guide on its usage, applications, and significance through detailed examples.

Understanding type() Function

The type() function in Python is used to get the type of an object or create new object types. Its syntax is straightforward:

type(object)
Python

Here, object represents the object whose type is to be determined.

Example 1: Getting the Type of an Object

num = 10
print("Type of num:", type(num))
Python

Output 1:

Type of num: <class 'int'>
Bash

Example 2: Checking Type Equality

num = 10
if type(num) == int:
    print("num is an integer")
else:
    print("num is not an integer")
Python

Output 2:

num is an integer
Bash

Example 3: Creating New Object Types

MyClass = type('MyClass', (object,), {'attr': 'value'})
obj = MyClass()
print("Type of obj:", type(obj))
print("Attribute of obj:", obj.attr)
Python

Output 3:

Type of obj: <class '__main__.MyClass'>
Attribute of obj: value
Bash

Points to Remember

  • The type() function is used to get the type of an object or create new object types dynamically.
  • It is commonly used for dynamic type checking and object creation in Python.
  • type() can be used in various scenarios, including type comparison, object creation, and metaprogramming.
Author: user