Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How we can instantiate different python classes dynamically?
Dynamic class instantiation allows you to create objects from classes whose names are determined at runtime. This is useful for plugin systems, factories, and configuration-driven applications where the class to instantiate is not known until execution time.
Getting a Class by String Name
To instantiate a class dynamically, we first need to retrieve the class object using its string name ?
def get_class(kls):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
# Example: Get the datetime class
class_name = "datetime.datetime"
datetime_class = get_class(class_name)
print(datetime_class)
<class 'datetime.datetime'>
Instantiating Classes Dynamically
Once we have the class object, we can create instances with or without arguments ?
def get_class(kls):
parts = kls.split('.')
module = ".".join(parts[:-1])
m = __import__(module)
for comp in parts[1:]:
m = getattr(m, comp)
return m
# Get the datetime class and create instances
datetime_class = get_class("datetime.datetime")
# Create instance without arguments (current time)
current_time = datetime_class.now()
print("Current time:", current_time)
# Create instance with arguments
specific_date = datetime_class(2024, 1, 15, 10, 30)
print("Specific date:", specific_date)
Current time: 2024-01-15 14:25:30.123456 Specific date: 2024-01-15 10:30:00
Alternative Methods
Using getattr() for Built-in Classes
For classes in the same module or built-in classes, you can use getattr() ?
import datetime
# Get class by name from a module
class_name = "datetime"
dynamic_class = getattr(datetime, class_name)
# Create instance
new_date = dynamic_class(2024, 12, 25)
print("Christmas 2024:", new_date)
Christmas 2024: 2024-12-25 00:00:00
Using globals() and locals()
For classes in the current namespace, use globals() or locals() ?
class CustomClass:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, I'm {self.name}"
# Get class from globals
class_name = "CustomClass"
dynamic_class = globals()[class_name]
# Create instance
obj = dynamic_class("Dynamic Object")
print(obj.greet())
Hello, I'm Dynamic Object
Practical Example
Here's a factory pattern using dynamic instantiation ?
class Dog:
def __init__(self, name):
self.name = name
def sound(self):
return "Woof!"
class Cat:
def __init__(self, name):
self.name = name
def sound(self):
return "Meow!"
def create_animal(animal_type, name):
# Get class from globals
animal_class = globals()[animal_type]
return animal_class(name)
# Create animals dynamically
dog = create_animal("Dog", "Rex")
cat = create_animal("Cat", "Whiskers")
print(f"{dog.name} says: {dog.sound()}")
print(f"{cat.name} says: {cat.sound()}")
Rex says: Woof! Whiskers says: Meow!
Conclusion
Dynamic class instantiation is achieved by first obtaining the class object using __import__(), getattr(), or namespace lookups, then calling it like a regular constructor. This technique is essential for building flexible, configuration-driven applications.
