How to create inline objects with properties?

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

In Javascript it would be:

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


        
9条回答
  •  无人及你
    2020-12-04 19:44

    SilentGhost had a good answer, but his code actually creates a new object of metaclass type, in other words it creates a class. And classes are objects in Python!

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

    gives

    
    

    To create a new object of a custom or build-in class with dict attributes (aka properties) in one line I'd suggest to just call it:

    new_object = type('Foo', (object,), {'name': 'new object'})()
    

    and now

    type(new_object) 
    

    is

    
    

    which means it's an object of class Foo

    I hope it helps those who are new to Python.

提交回复
热议问题