Junior — Middle
What is the role of the type() function in Python and how does it work in different scenarios?
sobes.tech AI
Answer from AI
The type() function in Python is used to determine the type of an object or to dynamically create new types.
- When called with one argument,
type(obj)returns the class (type) of the objectobj.
print(type(123)) # <class 'int'>
print(type('hello')) # <class 'str'>
- When called with three arguments,
type(name, bases, dict)creates a new type (class) with the namename, inheriting frombases, and with attributes from the dictionarydict.
MyClass = type('MyClass', (object,), {'x': 5, 'hello': lambda self: 'Hi'})
obj = MyClass()
print(obj.x) # 5
print(obj.hello()) # Hi
Thus, type() is useful both for checking an object's type and for metaprogramming and dynamic class creation.