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

前端 未结 11 908
谎友^
谎友^ 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:14

    This is the shortest way I know

    >>> obj = type("myobj",(object,),dict(foo=1,bar=2))
    >>> obj.foo
    1
    >>> obj.bar
    2
    >>> 
    

    using dict instead of {} insures your attribute names are valid

    >>> obj = type("myobj",(object,),{"foo-attr":1,"bar-attr":2})
    >>> obj.foo-attr
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: type object 'myobj' has no attribute 'foo'
    >>>
    

提交回复
热议问题