Is it possible to create anonymous objects in Python?

前端 未结 11 586
余生分开走
余生分开走 2020-12-14 13:58

I\'m debugging some Python that takes, as input, a list of objects, each with some attributes.

I\'d like to hard-code some test values -- let\'s say, a list of four

11条回答
  •  既然无缘
    2020-12-14 14:35

    As of Python 3.3, there's types.SimpleNamespace that does exactly what you want:

    myfunc([types.SimpleNamespace(foo=1), types.SimpleNamespace(foo=2), types.SimpleNamespace(foo=3), types.SimpleNamespace(foo=4)])
    

    That's a tad wordy, but you can clean it up with an alias:

    _ = types.SimpleNamespace
    myfunc([_(foo=1), _(foo=2), _(foo=3), _(foo=4)])
    

    And now that's actually pretty close to the fictional syntax in your question.

提交回复
热议问题