有时我需要在python中创建一个匿名类实例,就像C#:
var o= new {attr1="somehing", attr2=344};
但是在python中我以这种方式做到了:
class Dummy: pass
o = Dummy()
o.attr1 = 'something'
o.attr2 = 344
#EDIT 1
print o.attr1, o.attr2
如何在单个语句中以pythonic方式做到这一点?
最佳答案
o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 })
o.attr3 = "test"
print o.attr1, o.attr2, o.attr3