Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an anonymous class instance in python

Tags:

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?

like image 437
pylover Avatar asked Dec 15 '12 23:12

pylover


People also ask

How do you make an anonymous class in Python?

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.

What is an anonymous class?

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.

How do you create a dynamic object in Python?

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.

Can an object be anonymous?

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.


1 Answers

o = type('Dummy', (object,), { "attr1": "somehing", "attr2": 344 }) 
o.attr3 = "test" print o.attr1, o.attr2, o.attr3 
like image 66
rid Avatar answered Sep 19 '22 18:09

rid