The type()
function is used to check the type/class of the object passed in as an argument. It is also used with three arguments to create a new type as we will see later.
type(obj)
copy
obj |
The object whose type is to be checked. |
We can use the type()
function to check whether two values are of the same type. for Example:
The function is also used to check explicitly whether a given value is an instance of a particular class.
The type() Function for creating a new type
The type()
function can be used with three arguments in an entirely different context from the one described above. With three arguments, the function is used to create a class dynamically. The syntax for creating a class using type()
function is as follows:
type(name, bases, class_dict, **kwargs)
copy
name | This is a string that represents the name of the class you want to create. |
bases | This argument represents the base classes or parent classes that the new class inherits from. It can be a single base class or a tuple of base classes. If the class has no base classes, you can pass an empty tuple () . |
class_dict | This argument represents a dictionary that contains the attributes and methods of the class. The dictionary maps attribute names (as strings) to their corresponding values (e.g., variables, functions). |
**kwargs | Any other additional arbitrary keyword arguments. |
The function returns the newly created class.