Is it possible to create anonymous objects in Python?

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

    Non classy:

    def mock(**attrs):
        r = lambda:0
        r.__dict__ = attrs
        return r 
    
    def test(a, b, c, d):
        print a.foo, b.foo, c.foo, d.foo
    
    test(*[mock(foo=i) for i in xrange(1,5)])
    # or
    test(mock(foo=1), mock(foo=2), mock(foo=3), mock(foo=4))
    

提交回复
热议问题