Category: python
Reflection in Python
Published on 23 Oct 2026
Explanation
Reflection in Python is the ability
of a program to inspect its
own objects, classes, functions, and attributes
at runtime. Python provides built-in functions
such as type(), dir(), getattr(), and
hasattr() to examine objects dynamically. Reflection
is useful in frameworks, debugging, dynamic
programming, and plugin systems.
Code:
class Student:
name = "Praveen"
student = Student()
print(type(student))
print(dir(student))
print(hasattr(student, "name"))
Explanation
Python provides the dir() function to
list the available attributes and methods
of an object. The type() function
identifies an object's type, while vars()
returns an object's __dict__ when available.
These functions help developers
understand objects
at runtime.
Code:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
employee = Employee("Arun", 50000)
print(type(employee))
print(vars(employee))
print(dir(employee))
Explanation
The getattr() function retrieves an attribute
by its name as a string.
It can also accept a default
value if the attribute does not
exist. This is useful when attribute
names are determined dynamically at runtime.
Code:
class Student:
name = "Arun"
age = 25
student = Student()
attribute = "name"
print(getattr(student, attribute))
print(getattr(student, "city", "Not Available"))
Explanation
Python allows methods to be accessed
dynamically using getattr(). After retrieving a
method, you can call it with
the required arguments. This technique is
useful for command handlers, plugin systems,
and applications that select behavior based
on user input or configuration.
Code:
class Calculator:
def add(self, a, b):
return a + b
def multiply(self, a, b):
return a * b
calculator = Calculator()
method_name = "add"
method = getattr(calculator, method_name)
print(method(10, 20)) # 30
Explanation
Reflection is used in Python frameworks,
serializers, testing tools, dependency injection systems,
and dynamic plugin architectures. For example,
a framework can inspect a class
to find methods or attributes and
invoke them dynamically. Use reflection carefully,
because dynamically accessing or calling attributes
can make code harder to understand
and may introduce security risks when
names come from untrusted input.
Code:
class UserService:
def get_users(self):
return ["Arun", "Priya"]
def get_roles(self):
return ["Admin", "Developer"]
service = UserService()
action = "get_users"
if hasattr(service, action):
method = getattr(service, action)
if callable(method):
print(method())