Python type() FunctionThe 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. Syntax:Parameters: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. Returns: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. Python type() Function: Single argumentLet's see an example of the type() function when single argument is passed: Code 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. Python type() Function: Three argumentsLet's see an example of the type() function when three arguments are passed: Code 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' >. Python type() Function ExampleThe below example shows how to get the type of an object. Code 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. Then, we have defined a class named as Python and produced an InstanceOfPython which prints its type. Conclusion:In conclusion, the type() function in Python is a built-in function that is utilised to find out the type of an object or to create a new class in a dynamic way. The type() function takes one or three arguments and is a useful asset for metaprogramming in Python. Next TopicPython Built in Functions |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India