Learn Python
>>> oop_advanced.reflection

Reflection & Introspection in Python

#concept

Reflection (or introspection) means a program examining or manipulating its own objects, classes, and code at runtime — asking what type something is, what attributes or methods it has, or even changing them dynamically. Python is unusually open to this: dir(), type(), getattr(), setattr(), and hasattr() are all built-in tools for looking inside any object while a program runs.

#how it works
1

type(obj) reveals the exact class

Confirms precisely what kind of object something is.

2

dir(obj) lists everything available

Every attribute and method name accessible on an object.

3

hasattr(obj, "name") checks safely

Whether an attribute or method exists, without risking an error by just trying to access it.

4

getattr(obj, "name", default) retrieves by string name

With an optional fallback if the attribute doesn’t exist.

5

setattr(obj, "name", value) sets by string name

Exactly as if instance.name = value had been written directly.

#example
class Dog:
def __init__(self, name):
self.name = name
 
def bark(self):
print("Woof!")
 
rex = Dog("Rex")
 
print(hasattr(rex, "bark"))
print(getattr(rex, "name"))
 
setattr(rex, "age", 3)
print(rex.age)
Output
True
Rex
3
1hasattr(rex, "bark") checks whether rex has a bark attribute (it does, as a method), returning True.
2getattr(rex, "name") retrieves the name attribute by its string name, exactly as rex.name would, returning "Rex".
3setattr(rex, "age", 3) dynamically adds a brand new age attribute to rex, as if rex.age = 3 had been written directly.
4Printing rex.age afterward confirms the dynamically added attribute is now a genuine part of the object.
#use cases
Writing generic debugging or logging tools that can inspect any object without knowing its type in advance
Building frameworks that dynamically configure objects based on data, like an ORM mapping database columns to attributes
Checking whether an object supports an optional method before calling it, using hasattr()
Serialization libraries that need to read every attribute off an arbitrary object to convert it to JSON or another format

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.