How to create objects on the fly in python?

前端 未结 8 2191
野的像风
野的像风 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:25

    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.

    0 讨论(0)
  • 2020-12-17 10:30

    for the sake of completeness, there is also recordclass:

    from recordclass import recordclass
    Test = recordclass('Test', ['test', 'test1', 'test2'])
    foo = Test(test=['a1','a2','b2'], test1='someting else', test2=1)
    
    print(foo.test)
    .. ['a1', 'a2', 'b2']
    
    0 讨论(0)
提交回复
热议问题