What is reflection in Python OOP?
a) The ability of a program to inspect and modify its own structure and behavior at runtime
b) A type of inheritance
c) A method for reversing a string
d) A technique for encrypting data
Answer:
a) The ability of a program to inspect and modify its own structure and behavior at runtime
Explanation:
Reflection in Python OOP is the ability of a program to inspect and modify its own structure and behavior at runtime. This includes examining the attributes, methods, and classes of objects, as well as dynamically invoking methods or modifying properties.
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
print(f"Hello, {self.name}!")
# Using reflection to inspect the class
obj = MyClass("Alice")
print(hasattr(obj, 'name')) # Output: True
print(getattr(obj, 'name')) # Output: Alice
setattr(obj, 'name', 'Bob')
print(obj.name) # Output: Bob
In this example, reflection is used to check if the name
attribute exists, retrieve its value, and modify it at runtime. Reflection provides powerful capabilities for metaprogramming, allowing programs to adapt dynamically based on their structure and behavior.
Reflection is useful in scenarios where you need to write flexible and dynamic code, such as frameworks, libraries, and tools that operate on other Python code.