The type() function in Python is a built-in function that returns the type of the predetermined object or constructs another class dynamically.
The type() function is regularly utilised in metaprogramming, where projects can adjust themselves during runtime. Using the type() function, a program can dynamically build new classes and change existing ones. This is particularly valuable in libraries and frameworks where new classes should be made depending on the input of the user.
It has the following syntax:
It has the following syntax:
object: The type() returns the type of this object if one parameter is specified.
name (optional): It is the name of the class.
bases (optional): It specifies the base classes.
dict (optional): It specifies the namespace with the definition for the class.
It returns the type of the specified object if a single argument is passed to the type(). If three arguments are passed, it returns a new type of object.
Here, we are going to discuss several examples that demonstrate the working of type() Function.
In this example, the type() function is used with a single argument to determine the data type of a variable.
Output:
< class 'str'>
Explanation:
In the above example, we have utilised the type() function to find out the type of the string object my_word. The type() function returns < class ' str '>, showing that my_word is a string object.
In this example, the type() function is used with three arguments to dynamically create a new class and then check its type.
Output:
< class 'type'>
Explanation:
In the above example, we have utilised the type() function to create another new class, BaseClass. We have passed three arguments to the type() function: the name of the new class BaseClass, a void tuple showing that there are no base classes, and a word reference "a" with a value of 100. At last, we have printed the type of the BaseClass object utilising the type() function, which returns <class 'type' >.
In this example, the type() function is used to check the data types of different objects such as a list, dictionary, and a class instance.
Output:
<class 'list'> <class 'dict'> <class '__main__.Python'>
Explanation:
In the above example, we have taken a list object 'List' that contains some values, and in return, it prints the type of the List. In the second case, we have taken a dictionary object 'Dict' that contains some values, and in return, it prints the type of the Dict. After that, we have defined a class named as Python and produced an InstanceOfPython which prints its type.
We request you to subscribe our newsletter for upcoming updates.