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)
obj |
The object whose type is to be checked. |
Examples:
type("Hello")
//<class 'str'>
type(9)
//<class 'int'>
type(9.5)
//<class 'float'>
type([1, 2, 3])
//<class 'list'>
type(type)
//<class 'type'>
type(print)
//<class 'builtin_function_or_method'>
import math
type(math)
//<class 'module'>
We can use the type() function to check whether two values are of the same type. for Example:
type(9) == type(9.5)
//False
type("Hello") == type("World")
//True
The function is also used to check explicitly whether a given value is an instance of a particular class.
type(5) == int
//True
type("Hello") == str
//True
type([1, 2]) == set
//False
type([1, 2]) == list
//True
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)
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.
Example:
#Define the constructor for the function.
def init(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
Person = type("Person", (), {'__init__':init ,'__str__':lambda self: "{}, {} - {}".format(self.name, self.age, self.gender)})
p = Person('John', 30, 'Male')
print(p)