pylover pylover - 1 year ago 145
Python Question

Create an anonymous class instance in python

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
print o.attr1, o.attr2

how can do that in pythonic way in single statement?

rid rid
Answer Source
o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 })
o.attr3 = "test"
print o.attr1, o.attr2, o.attr3
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download