How to create objects on the fly in python?

前端 未结 8 2220
野的像风
野的像风 2020-12-17 09:34

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],          


        
8条回答
  •  庸人自扰
    2020-12-17 10:21

    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.

提交回复
热议问题