The type() function is used to get the type of an object or to dynamically create a new class.
Function Syntax
This function has two uses:
1. Get the Type of an Object
type(object)
The function returns the type of object.
2. Dynamically Create a Class
type(name, bases, dict)
Parameters:
name: The name of the class to create.bases: A tuple containing the parent classes to inherit from.dict: A dictionary containing attributes and methods.
The function returns a newly created class.
Examples of the type() Function
Checking the types of different objects:
print(type(123)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type((1, 2, 3))) # <class 'tuple'>
print(type({"a": 1})) # <class 'dict'>
print(type(True)) # <class 'bool'>
import math
print(type(math)) # <class 'module'>
When three arguments are passed, a class can be dynamically created:
MyClass = type('MyClass', (), {'x': 10})
obj = MyClass()
print(obj.x) # 10
Creating a class with methods:
def child_init(self):
super(Child,self).__init__()
self.y = 20
def say(self):
print("hello!")
class Parent:
def __init__(self):
self.x = 10
Child = type('Child', (Parent,), {
'__init__': child_init,
'say': say
})
obj = Child()
print(obj.x) # 10
print(obj.y) # 20
obj.say() # hello!