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
How to convert a string to a Python class object?
Let's understand the title: 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. In this article, we will discuss different ways to convert a string to a Python class object.
Using globals() Function
The globals() function is used to convert a string to a Python class object when a class is in global scope.
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))
Following is the output of the above code -
Bike started! <class '__main__.Bike'>
Using locals() Function
The locals() function is used to convert a string to a Python class object when a class is in local scope (like inside a function).
def create_object():
class Animal:
def bark(self):
print("Iam an Animal")
class_name = "Animal"
cls = locals()[class_name]
obj = cls()
obj.bark()
print(type(obj))
create_object()
Following is the output of the above code -
Iam an Animal <class '__main__.create_object.<locals>.Animal'>
Using getattr() Function
The getattr() is used when the class is defined in another module. Let us assume we have the following program in a file named "Python.py".
# In another file (say `Python.py`)
class Tutorialspoint:
def Python(self):
print("Hello welcome to Python Tutorial")
We can use the getattr() function to create its instance if the call is created in a separate module -
import Python class_name = "Tutorialspoint" cls = getattr(Python, class_name) obj = cls() obj.Python()
Following is the output of the above code -
Hello welcome to Python Tutorial <class 'Python.Tutorialspoint'>
