How to create inline objects with properties?

后端 未结 9 708
误落风尘
误落风尘 2020-12-04 19:12

In Javascript it would be:

var newObject = { \'propertyName\' : \'propertyValue\' };
newObject.propertyName;  // retur         


        
9条回答
  •  温柔的废话
    2020-12-04 19:42

    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.

提交回复
热议问题