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?
If you want the instance to be anonymous as well (using the object directly in an expression), then you're bound to use the type-expression. However in many cases the instance will not be anonymous, but assigned to a variable. This case can be handled in a reasonable way in python by using metaclasses or decorators.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final. Like a nested class, a declaration of a type (such as a variable) in an anonymous class shadows any other declarations in the enclosing scope that have the same name.
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
Object expressions You can define them from scratch, inherit from existing classes, or implement interfaces. Instances of anonymous classes are also called anonymous objects because they are defined by an expression, not a name.
o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 })
o.attr3 = "test" print o.attr1, o.attr2, o.attr3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With