The type() function in Python is used to get the type of an object or to create a new class dynamically.
When used with an object, the type() function returns the type of the object. For example:
a = 5 print(type(a)) # Output:
When used with three arguments, type() creates a new class. The three arguments are the name of the new class, a tuple of the base classes (which can be empty), and a dictionary containing the attributes of the new class.
For example, the following code creates a new class called Person with two attributes: name and age:
Person = type('Person', (), {'name': 'John', 'age': 30}) print(type(Person)) # Output:
Here, we pass the name of the new class as the first argument, an empty tuple as the second argument (since Person does not inherit from any other class), and a dictionary containing the attributes of the new class (in this case, name and age).
The type() function is commonly used in Python to create new classes dynamically, as well as to check the type of an object.
0 Comments