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 to convert a string to a Python class object?
Converting a string to a Python class means accessing a Python class using its name stored as a string, allowing dynamic creation of objects at runtime. This is useful for factory patterns, plugin systems, and configuration-driven object creation.
Using globals() Function
The globals() function retrieves classes from the global namespace using their string names ?
class Bike:
def start(self):
print("Bike started!")
class_name = "Bike"
cls = globals()[class_name] # Convert string to class
obj = cls()
obj.start()
print(type(obj))
The output of the above code is ?
Bike started! <class '__main__.Bike'>
Using locals() Function
The locals() function accesses classes from the local scope, such as classes defined inside functions ?
def create_object():
class Animal:
def bark(self):
print("I am an Animal")
class_name = "Animal"
cls = locals()[class_name]
obj = cls()
obj.bark()
print(type(obj))
create_object()
The output of the above code is ?
I am an Animal <class '__main__.create_object.<locals>.Animal'>
Using getattr() Function
The getattr() function retrieves classes from imported modules. First, create a file named mymodule.py ?
# mymodule.py
class Tutorialspoint:
def greet(self):
print("Hello welcome to Python Tutorial")
Then import and access the class dynamically ?
import mymodule class_name = "Tutorialspoint" cls = getattr(mymodule, class_name) obj = cls() obj.greet() print(type(obj))
The output of the above code is ?
Hello welcome to Python Tutorial <class 'mymodule.Tutorialspoint'>
Using eval() Function (Not Recommended)
The eval() function can dynamically evaluate class names, but it's unsafe for untrusted input ?
class Car:
def drive(self):
print("Car is driving")
class_name = "Car"
cls = eval(class_name) # Security risk with untrusted input
obj = cls()
obj.drive()
print(type(obj))
The output of the above code is ?
Car is driving <class '__main__.Car'>
Comparison
| Method | Scope | Use Case | Security |
|---|---|---|---|
globals() |
Global | Classes in current module | Safe |
locals() |
Local | Classes in local scope | Safe |
getattr() |
Module | Classes in imported modules | Safe |
eval() |
Any | Dynamic evaluation | Unsafe |
Conclusion
Use globals() for global classes, locals() for local classes, and getattr() for module classes. Avoid eval() due to security risks with untrusted input.
