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'
Solution 1:
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.
Solution 2:
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.
Solution 3:
There is another solution in Python 3.3+types.SimpleNamespace
from types import SimpleNamespace
test_obj = SimpleNamespace(a=1, b=lambda: {'hello': 42})
test_obj.a
test_obj.b()
Solution 4:
Solution 5:
use building function type: document
>>>classX:... a = 1...>>>X = type('X', (object,), dict(a=1))
first and second X are identical
Post a Comment for "How To Create Objects On The Fly In Python?"