Sobes.tech
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.

  1. When called with one argument, type(obj) returns the class (type) of the object obj.
print(type(123))        # <class 'int'>
print(type('hello'))    # <class 'str'>
  1. When called with three arguments, type(name, bases, dict) creates a new type (class) with the name name, inheriting from bases, and with attributes from the dictionary dict.
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.