How to Create a Python Class from a String?

Estimated read time 2 min read

In Python, you can dynamically create a class from a string using the type() function. The type() function takes three arguments: the name of the class, a tuple of the base classes the new class should inherit from (which can be an empty tuple if you don’t want to inherit from any classes), and a dictionary containing the attributes and methods of the class.

Here’s an example of how you might create a Python class from a string:

class_str = '''
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height
'''

exec(class_str)
my_rect = Rectangle(5, 10)
print(my_rect.area())

In this example, we define a string class_str that contains the definition of a Rectangle class with an __init__() method and an area() method.

We then use the exec() function to execute the string as Python code, which creates the Rectangle class and makes it available for use in our program.

We can then create an instance of the Rectangle class and call its area() method to calculate the area of a rectangle with width 5 and height 10.

Note that using exec() to execute a string as Python code can be risky, as it could potentially execute malicious code. If you need to create a class dynamically in your Python program, you should make sure that the string you’re executing is trusted and comes from a trusted source.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply