How do I create objects on the fly in Python? I often want to pass information to my Django templates which is formatted like this:
{'test': [a1, a2, b2], 'test2': 'something else', 'test3': 1}
which makes the template look untidy. so I think it's better to just create an object which is like:
class testclass(): self.test = [a1,a2,b2] self.test2 = 'someting else' self.test3 = 1 testobj = testclass()
so I can do:
{{ testobj.test }} {{ testobj.test2 }} {{ testobj.test3 }}
instead of calling the dictionary.
Since I just need that object once, is it possible to create it without writing a class first? Is there any short-hand code? Is it ok to do it like that or is it bad Python?
Creating an Object in Python It can also be used to create new object instances (instantiation) of that class. The procedure to create an object is similar to a function call. This will create a new object instance named harry . We can access the attributes of objects using the object name prefix.
List object is the more general sequence provided by Python. Lists are ordered collections of arbitrarily typed objects. They have no fixed size. In other words, they can hold arbitrary objects and can expand dynamically as new items are added.
We already know that an object is a container of some data and methods that operate on that data. In Python, an object is created from a class. To create an object, you have to define a class first.
You can use built-in type function:
testobj = type('testclass', (object,), {'test':[a1,a2,b2], 'test2':'something else', 'test3':1})()
But in this specific case (data object for Django templates), you should use @Xion's solution.
In Django templates, the dot notation (testobj.test
) can resolve to the Python's []
operator. This means that all you need is an ordinary dict:
testobj = {'test':[a1,a2,b2], 'test2':'something else', 'test3':1}
Pass it as testobj
variable to your template and you can freely use {{ testobj.test }}
and similar expressions inside your template. They will be translated to testobj['test']
. No dedicated class is needed here.
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