Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create objects on the fly in python?

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?

like image 938
JasonTS Avatar asked Dec 20 '11 13:12

JasonTS


People also ask

Can you create an object in a function 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.

What are the objects in a list Python?

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.

Can we create object without class in Python?

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.


2 Answers

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.

like image 51
number5 Avatar answered Sep 22 '22 17:09

number5


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.

like image 41
Xion Avatar answered Sep 18 '22 17:09

Xion