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

前端 未结 11 907
谎友^
谎友^ 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条回答
  •  感情败类
    2021-02-01 15:19

    type('', (), {})() will create an object that can have arbitrary attributes.

    Example:

    obj = type('', (), {})()
    obj.hello = "hello"
    obj.world = "world"
    print obj.hello, obj.world #will print "hello world"
    

    type() with three arguments creates a new type.

    The first argument '' is the name of the new type. We don't care about the name, so we leave it empty.

    The second argument () is a tuple of base types, here object (implicit).

    The third argument is a dictionary of attributes of the new object - again we don't care to it's an empty dictionary {}

    And in the end we instantiate a new instance of this new type with () at the end.

提交回复
热议问题