如何在python中动态创建对象? [英] How to create objects on the fly in python?
本文介绍了如何在python中动态创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python中动态创建对象?我经常想将信息传递给Django模板,其格式如下:
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()
所以我可以这样做:
{{ testobj.test }}
{{ testobj.test2 }}
{{ testobj.test3 }}
而不是调用字典。
由于我只需要该对象一次,是否可以在不首先编写类的情况下创建它?有速记代码吗?可以那样做还是不好用?
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?
推荐答案
您可以使用内置的类型函数:
testobj = type('testclass', (object,),
{'test':[a1,a2,b2], 'test2':'something else', 'test3':1})()
但是在这种特定情况下(Django模板的数据对象),您应该使用@Xion的解决方案。
But in this specific case (data object for Django templates), you should use @Xion's solution.
这篇关于如何在python中动态创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文