Python type() Method
The type()
method either returns the type of the specified object or returns a new type object of the specified dynamic class, based on the specified class name, base classes and class body.
Syntax:
type(object)
type(name, bases, dict)
Parameters:
- object: Required. The object whose type is to be returned.
- name: Required. A class name.
- bases: Required. A tuple that itemizes the base class.
- dict: Required. A dictionary which is the namespace containing definitions for the class body.
Return Value:
- If object is passed, then it returns the type of object in angular brackets as <class 'name of the class'>.
- If name, bases and dict are passed, then it returns a new type object.
The following method returns the type of various objects.
lang = 'Python'
nums = [1,2,3,4]
nums_dict = {'one':1,'two':2,'three':3}
print(type(nums))
print(type(lang))
print(type(nums_dict))
<class 'str'> <br>
<class 'list'><br>
<class 'dict'>
In the above example, an object is passed as a single parameter in the type()
function, so it returns the class name of the object e.g. for string, it returns <class 'str'>
. Use the isinstance() function to test object's type if you want to consider base classes also.
The type()
method can be used to create a new class dynamically instead of using the class statement. For example, the following creates the student
class dynamically by passing name, base, and dict paramters to the type()
function.
std = type('student', (object,), dict(name='John', age=12))
print(std.name)
print(std.age)
John
12
The type of the new object created using the type()
function will be type
. The __name__
attribute of the employee
class will be employee
, a tuple (object,)
specifies the base class of the employee
class and will assign to the __bases__
attribute. The third parameter dict(name='John', age=12)
becomes the body of the class that contains two attributes name
and age
. This dict will be assigned to the __dict__
attribute.
std = type('student', (object,), dict(name='John', age=12))
print('Type = ', type(std))
print('__name__ = ', std.__name__)
print('__bases__ = ', std.__bases__)
print('__dict__ = ', std.__dict__)
Type = <class 'type'>
name = student
bases = (<class 'object'>,)
dict = mappingproxy({'name': 'bill', 'age': 22, 'module': 'main', 'dict': <attribute 'dict' of 'employee' objects>, 'weakref': <attribute 'weakref' of 'employee' objects>, 'doc': None})
The dir function will returns the following attributes of the dynamic class created using the type()
function.
std = type('student', (object,), dict(name='John', age=12))
dir(std)
['class', 'delattr', 'dict', 'dir', 'doc', 'eq', 'format', 'ge', 'getattribute', 'gt', 'hash', 'init', 'init_subclass', 'le', 'lt', 'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', 'subclasshook', 'weakref', 'age', 'name']