The built-in function type() is used to return the type of specified object it also allows to return of a new type object based on the given arguments.
type(object) #where object is whoes type needs to be return
type(name, bases, dict)
Takes three parameters. The type() function helps to print the type of the parameters when validation fails.
Parameter | Description | Required / Optional |
---|---|---|
name | a class name; becomes the __name__ attribute | Required |
bases | a tuple that itemizes the base class; becomes the __bases__ attribute | Optional |
dict | a dictionary which is the namespace containing definitions for the class body; becomes the __dict__ attribute. | Optional |
If a single parameter is passed its value is the same as the object.__class__ instance variable. If three parameters are passed it creats a new class dynamically.
Input | Return Value |
---|---|
If object only | type of object |
If 3 parameters | a new type object |
number_list = [3, 4]
print(type(number_list))
number_dict = {3: 'three', 4: 'four'}
print(type(number_dict))
class Foo:
a = 0
foo = Foo()
print(type(foo))
Output:
< class 'list'> < class 'dict'> < class '__main__.Foo'>
obj1 = type('X', (object,), dict(a='Foo', b=12))
print(type(obj1))
print(vars(obj1))
class test:
a = 'Fo'
b = 15
obj2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(obj2))
print(vars(obj2))
Output:
{'a': 'Fo', 'b': 15, '__module__': '__main__', '__dict__': , '__weakref__': , '__doc__': None} {'a': 'Fo', 'b': 15, '__module__': '__main__', '__doc__': None}