Is it possible to create anonymous objects in Python?

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

    anonymous_object = type('',(),{'name':'woody', 'age':'25'})()
    anonymous_object.name
    > 'woody'
    

    There is a cool way but hard to understand. It use type() create a no-named class with default init params, then init it without any param and get the anonymous object.

提交回复
热议问题