Python’s reflection capabilities are often associated with its ability to dynamically inspect and manipulate objects at runtime. Here are a few ways reflection can be achieved in Python:
-
type()
Function:- The
type()
function in Python can be used to get the type of an object. It’s a form of reflection that allows you to determine the class or type of an object.
pythonCopy code
x = 42 print(type(x)) # Output: <class 'int'>
- The
-
dir()
Function:- The
dir()
function returns a list of names in the current local scope or a list of attributes of an object. It provides a way to inspect the attributes and methods of an object.
pythonCopy code
x = "Hello" print(dir(x))
- The
-
getattr()
andsetattr()
Functions:- The
getattr()
function allows you to access the value of an attribute of an object by name, andsetattr()
allows you to set the value of an attribute.
pythonCopy code
- The
class MyClass:
def __init__(self):
self.my_attribute = 42
obj = MyClass()
print(getattr(obj, "my_attribute")) # Output: 42
setattr(obj, "my_attribute", 99)
print(obj.my_attribute) # Output: 99
-
inspect
Module:- The
inspect
module provides functions for introspecting objects, such as getting information about classes, functions, and modules.
- The
import inspect
def my_function(x, y):
return x + y
print(inspect.getargspec(my_function)) # Output: ArgSpec(args=['x', 'y'], varargs=None, keywords=None, defaults=None)
-
Metaclasses:
- Python supports metaclasses, which are classes for classes. Metaclasses allow you to customize the creation of classes and can be used for advanced reflection and introspection.
class MyMeta(type): def __new__(cls, name, bases, dct): # Custom logic for creating a class return super().__new__(cls, name, bases, dct) class MyClass(metaclass=MyMeta): pass
These examples showcase some of the reflection capabilities in Python. Reflection in Python is often leveraged for dynamic behavior, introspection, and metaprogramming. Keep in mind that Python’s dynamic nature allows for powerful reflection, but it’s essential to use it judiciously to maintain code readability and simplicity.