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

后端 未结 5 382
我在风中等你
我在风中等你 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:49

    Using an object just to hold values isn't the most Pythonic style of programming. It's common in programming languages that don't have good associative containers, but in Python, you can use use a dictionary:

    my_dict = {} # empty dict instance
    
    my_dict["foo"] = "bar"
    my_dict["num"] = 42
    

    You can also use a "dictionary literal" to define the dictionary's contents all at once:

    my_dict = {"foo":"bar", "num":42}
    

    Or, if your keys are all legal identifiers (and they will be, if you were planning on them being attribute names), you can use the dict constructor with keyword arguments as key-value pairs:

    my_dict = dict(foo="bar", num=42) # note, no quotation marks needed around keys
    

    Filling out a dictionary is in fact what Python is doing behind the scenes when you do use an object, such as in Ned Batchelder's answer. The attributes of his ex object get stored in a dictionary, ex.__dict__, which should end up being equal to an equivalent dict created directly.

    Unless attribute syntax (e.g. ex.foo) is absolutely necessary, you may as well skip the object entirely and use a dictionary directly.

提交回复
热议问题