How to create inline objects with properties?

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

In Javascript it would be:

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


        
相关标签:
9条回答
  • 2020-12-04 19:44

    I don't know if there's a built-in way to do it, but you can always define a class like this:

    class InlineClass(object):
        def __init__(self, dict):
            self.__dict__ = dict
    
    obj = InlineClass({'propertyName' : 'propertyValue'})
    
    0 讨论(0)
  • 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

    <class 'type'>
    

    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

    <class '__main__.Foo'>
    

    which means it's an object of class Foo

    I hope it helps those who are new to Python.

    0 讨论(0)
  • 2020-12-04 19:45

    Peter's answer

    obj = lambda: None
    obj.propertyName = 'propertyValue'
    
    0 讨论(0)
提交回复
热议问题