The type() function in Python tells what kind of data an object is or creates a new class dynamically. It is mainly used to identify data types at runtime and to build classes programmatically when needed.
Syntax
type(object)
type(name, bases, dict)
Parameters:
- object: The value or variable whose type you want to find
- name: Name of the class to create
- bases: Tuple of base classes
- dict: Dictionary containing class attributes
In the above example:
- The variable "x" is assigned the value 10.
- The type() function is used to find the data type of x.
- Returns int because 10 is an integer.
Examples
Example 1: Checks the data types of different Python values to show how type() identifies built-in data types.
Output<class 'int'>
<class 'str'>
<class 'list'>
In the above example:
- "a" is assigned the value 5, which is an integer.
- "b" is assigned the value "Hi", which is a string.
- "c" is assigned a list containing two elements, so its type is a list.
Example 2: Uses type() to compare whether two variables belong to the same data type.
In the above example:
- "x" is an integer, while "y" is a floating-point number.
- type(x) returns <class 'int'> and type(y) returns <class 'float'>.
- The is operator checks whether both types are the same object.
- Since int and float are different types, the expression evaluates to False.
Example 3: Shows how type() can dynamically create a new class with attributes.
Output<class '__main__.A'>
100
In the above example:
- type() is used here to dynamically create a class named A. "A" is the class name.
- () represents an empty tuple of base classes (so A inherits from object). {"x": 100} defines a class attribute x with the value 100.
- obj = A() creates an instance of the dynamically created class. type(obj) returns <class '__main__.A'>, showing that obj is an instance of class A.
- obj.x accesses the class attribute x, which prints 100.
Example 4: Checks whether two variables refer to objects of the same type using type() in a condition.
In the above example:
- "a" is a list, while "b" is a tuple.
- type(a) returns <class 'list'> and type(b) returns <class 'tuple'>.
- The == operator compares whether both types are the same.
- Since list and tuple are different data types, the expression evaluates to False.
Example 5: Uses type() to create a class with both data and a method dynamically.