Shortest way of creating an object with arbitrary attributes in Python?

前端 未结 11 1011
谎友^
谎友^ 2021-02-01 14:48

Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object shoul

11条回答
  •  旧时难觅i
    2021-02-01 15:12

    Use a combination between lambda and type build-in, I think is the smallest way to do that:

    obj = lambda **kwargs: type('obj', (object,), kwargs)()
    
    options = obj(do_good_stuff=True, do_bad_stuff=False)
    
    print options.do_good_stuff
    print options.do_bad_stuff
    

提交回复
热议问题