Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create inline objects with properties?

In Javascript it would be:

var newObject = { 'propertyName' : 'propertyValue' }; newObject.propertyName;  // returns "propertyValue" 

But the same syntax in Python would create a dictionary, and that's not what I want

new_object = {'propertyName': 'propertyValue'} new_object.propertyName  # raises an AttributeError 
like image 279
Jader Dias Avatar asked Oct 07 '09 00:10

Jader Dias


People also ask

What are inline objects?

Inline objects are embedded in the text flow. If you type more text above them, they are pushed along as the text grows. The selection handles on the top and left side of inline objects are inactive. You cannot drag these handles to resize the object; you can only resize it by dragging the active handles.

Can we create object without class in Python?

We already know that an object is a container of some data and methods that operate on that data. In Python, an object is created from a class. To create an object, you have to define a class first.


2 Answers

obj = type('obj', (object,), {'propertyName' : 'propertyValue'}) 

there are two kinds of type function uses.

like image 150
SilentGhost Avatar answered Sep 24 '22 08:09

SilentGhost


Python 3.3 added the SimpleNamespace class for that exact purpose:

>>> from types import SimpleNamespace  >>> obj = SimpleNamespace(propertyName='propertyValue') >>> obj namespace(propertyName='propertyValue')  >>> obj.propertyName 'propertyValue' 

In addition to the appropriate constructor to build the object, SimpleNamespace defines __repr__ and __eq__ (documented in 3.4) to behave as expected.

like image 24
Sylvain Leroux Avatar answered Sep 23 '22 08:09

Sylvain Leroux