I need to dynamically create a class. To go in futher detail I need to dynamically create a subclass of Django's Form
class.
By "dynamically" I intend to create a class based on configuration provided by a user.
e.g.
I want a class named CommentForm
which should subclass the Form
class.
The class should have a list of chosen attributes.
....in this case
name = forms.CharField() comment = forms.CharField(widget=forms.Textarea())
Any useful tips? :)
Dynamic Class Loading allows the loading of java code that is not known about before a program starts. Many classes rely on other classes and resources such as icons which make loading a single class unfeasible. For this reason the ClassLoader ( java. lang.
Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.
Classes are great if you need to keep state, because they containerize data (variables) and behavior (methods) that act on that data and should logically be grouped together. This leads to code that is better organized (cleaner) and easier to reuse.
A class is a code template for creating objects. Objects have member variables and have behaviour associated with them. In python a class is created by the keyword class .
You can create classes on the fly by calling the type
built-in, passing appropriate arguments along, like:
CommentForm = type("CommentForm", (Form,), { 'name': forms.CharField(), ... })
It works with new-style classes. I am not sure, whether this would also work with old-style classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With