How to create a new unknown or dynamic/expando object in Python

后端 未结 5 399
我在风中等你
我在风中等你 2021-02-02 07:07

In python how can we create a new object without having a predefined Class and later dynamically add properties to it ?

example:

dynamic_object = Dynami         


        
5条回答
  •  再見小時候
    2021-02-02 07:44

    Use the collections.namedtuple() class factory to create a custom class for your return value:

    from collections import namedtuple
    return namedtuple('Expando', ('dynamic_property_a', 'dynamic_property_b'))('abc', 'abcdefg')
    

    The returned value can be used both as a tuple and by attribute access:

    print retval[0]                  # prints 'abc'
    print retval.dynamic_property_b  # prints 'abcdefg'  
    

提交回复
热议问题