Header Ads Widget

⚡ Premium Tools Hub • EXE Apps + Full Python Source Code
Lite • Pro • Bundle Packs • Instant Download

Python Reflection (Complete Guide for Beginners)

 In Python, Reflection is a powerful feature that allows a program to inspect, analyze, and modify its own structure at runtime.

In simple terms:

Reflection means a program can look at itself and understand its classes, objects, methods, and attributes while it is running.


🔹 What is Reflection in Python?

Reflection is:

The ability of a program to examine and manipulate its own code during execution.

Python provides built-in functions to achieve reflection easily.


🔹 Why Use Reflection?

Reflection helps you to:

  • ✔ Inspect objects dynamically
  • ✔ Debug code easily
  • ✔ Build flexible frameworks
  • ✔ Create plugins or extensible systems
  • ✔ Work with unknown objects at runtime

🔹 Key Reflection Functions in Python

Python provides several built-in functions:

FunctionPurpose
type()Get type of object
id()Get memory address
dir()List all attributes/methods
getattr()Get attribute dynamically
setattr()Set attribute dynamically
hasattr()Check attribute exists
delattr()Delete attribute

🔹 1. Using type() for Reflection

x = 10
print(type(x))

Output:

<class 'int'>

👉 Shows object type dynamically


🔹 2. Using dir() to Inspect Object

class Student:
def __init__(self):
self.name = "John"

obj = Student()

print(dir(obj))

👉 This shows all attributes and methods available in the object.


🔹 3. Using getattr() (Dynamic Access)

class Student:
def __init__(self):
self.name = "Alice"

obj = Student()

print(getattr(obj, "name"))

Output:

Alice

🔹 4. Using setattr() (Dynamic Assignment)

class Student:
pass

obj = Student()

setattr(obj, "age", 20)

print(obj.age)

Output:

20

🔹 5. Using hasattr() (Check Attribute)

class Car:
def __init__(self):
self.brand = "Toyota"

c = Car()

print(hasattr(c, "brand"))
print(hasattr(c, "speed"))

Output:

True
False

🔹 6. Using delattr() (Delete Attribute)

class User:
def __init__(self):
self.name = "John"

u = User()

delattr(u, "name")

print(hasattr(u, "name"))

Output:

False

🔹 Real-Life Example of Reflection

Imagine a plugin system 🧩

Your main program does NOT know all features in advance.

It can:

  • Detect available plugins
  • Load them dynamically
  • Call their methods

Example:

class PluginA:
def run(self):
return "Plugin A running"

class PluginB:
def run(self):
return "Plugin B running"

Dynamic execution:

def execute(plugin):
if hasattr(plugin, "run"):
return getattr(plugin, "run")()

p = PluginA()
print(execute(p))

🔹 Output:

Plugin A running

🔹 Reflection with Classes

class Demo:
def hello(self):
return "Hello World"

obj = Demo()

print(dir(Demo)) # class info
print(dir(obj)) # object info

🔹 Reflection for Debugging

class Test:
def __init__(self):
self.x = 100

t = Test()

print(vars(t))

Output:

{'x': 100}

🔹 vars() vs dir()

FunctionPurpose
vars()Shows object attributes as dictionary
dir()Shows all methods + attributes

🔹 Advantages of Reflection

✅ 1. Dynamic programming

Code can adapt at runtime.

✅ 2. Better debugging

Inspect objects easily.

��� 3. Flexible frameworks

Used in Django, Flask, and plugins.

✅ 4. Code automation

Reduces hardcoding.


🔹 Disadvantages of Reflection

❌ 1. Slower performance

Runtime inspection costs speed.

❌ 2. Hard to debug

Dynamic behavior can be confusing.

❌ 3. Less readable code

Overuse reduces clarity.


🔹 When to Use Reflection?

Use reflection when:

  • Building frameworks
  • Creating plugin systems
  • Debugging complex objects
  • Working with unknown data structures

🔹 When NOT to Use

Avoid reflection when:

  • Simple direct code is enough
  • Performance is critical
  • Code readability is important

🚀 Conclusion

Python Reflection is a powerful feature that allows programs to inspect and manipulate themselves at runtime.

It makes Python:

  • Flexible
  • Dynamic
  • Powerful for frameworks

But it should be used carefully to avoid complexity.




Post a Comment

0 Comments