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)
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))
Output 1:
Type of num: <class 'int'>
Example 2: Checking Type Equality
num = 10
if type(num) == int:
print("num is an integer")
else:
print("num is not an integer")
Output 2:
num is an integer
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)
Output 3:
Type of obj: <class '__main__.MyClass'>
Attribute of obj: value
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.