Create an anonymous class instance in python

pylover picture pylover · Dec 16, 2012 · Viewed 13.9k times · Source

Sometimes i need to create an anonymous class instance in python, just like c#:

var o= new {attr1="somehing", attr2=344};

but in python i do it in this way:

class Dummy: pass
o = Dummy()
o.attr1 = 'something'
o.attr2 = 344
#EDIT 1
print o.attr1, o.attr2

how can do that in pythonic way in single statement?

Answer

rid picture rid · Dec 16, 2012
o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 })
o.attr3 = "test"
print o.attr1, o.attr2, o.attr3