Generating a class with methods
In this section, let us generate code for a class and its methods. Throughout this chapter, our goal is to generate code dynamically for building applications that can solve a specific purpose. Adding methods along with attributes makes the code generation for a class even more application-specific. We can look at two variations of this example:
- Generating a class with an
init
method - Generating a class with a user-defined method
Let’s discuss each in detail.
Generating a class with an init method
In this example, let us generate code for a class and add an init
method to the class and also initialize attributes. In this example, we will define a class for the vegetable counter of ABC Megamart. In the init
method, let us initialize cart items from the vegetable counter of ABC Megamart in this class:
classname = "VegCounter"
classtemplate = '''class ''' +classname...