Is it possible to create anonymous objects in Python?

前端 未结 11 598
余生分开走
余生分开走 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:45

    Another obvious hack:

    class foo1: x=3; y='y'
    class foo2: y=5; x=6
    
    print(foo1.x, foo2.y)
    

    But for your exact usecase, calling a function with anonymous objects directly, I don't know any one-liner less verbose than

    myfunc(type('', (object,), {'foo': 3},), type('', (object,), {'foo': 4}))
    

    Ugly, does the job, but not really.

提交回复
热议问题