How to create objects on the fly in python?

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

    The code below also require a class to be created however it is shorter:

     >>>d = {'test':['a1','a2','b2'], 'test2':'something else', 'test3':1}
     >>> class Test(object):
     ...  def __init__(self):
     ...   self.__dict__.update(d)
     >>> a = Test()
     >>> a.test
     ['a1', 'a2', 'b2']
     >>> a.test2
     'something else'
    

提交回复
热议问题