Junior — Middle
Can you explain what introspection means in programming?
sobes.tech AI
Answer from AI
Introspection in programming is the ability of a program to examine its own structure at runtime. In Python, this means the ability to obtain information about object types, their attributes, methods, and other characteristics dynamically.
For example, using functions like type(), dir(), getattr(), you can find out what methods are available on an object or call them dynamically.
Example of introspection:
class MyClass:
def method(self):
pass
obj = MyClass()
print(type(obj)) # <class '__main__.MyClass'>
print(dir(obj)) # list of attributes and methods
print(hasattr(obj, 'method')) # True
method = getattr(obj, 'method')
method() # call the method dynamically
Introspection is useful for writing flexible and dynamic code, for example, in frameworks, tests, or when serializing objects.