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

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

    The original code can be streamlined a little by using __dict__:

    In [1]: class data:
       ...:     def __init__(self, **kwargs):
       ...:         self.__dict__.update(kwargs)
       ...: 
    
    In [2]: d = data(foo=1, bar=2)
    
    In [3]: d.foo
    Out[3]: 1
    
    In [4]: d.bar
    Out[4]: 2
    

    In Python 3.3 and greater, this syntax is made available by the types.SimpleNamespace class.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-01 15:13

    Use collections.namedtuple.

    It works well.

    from collections import namedtuple
    Data = namedtuple( 'Data', [ 'do_good_stuff', 'do_bad_stuff' ] )
    options = Data( True, False )
    
    0 讨论(0)
  • 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 "<stdin>", line 1, in <module>
    AttributeError: type object 'myobj' has no attribute 'foo'
    >>>
    
    0 讨论(0)
  • 2021-02-01 15:14

    You might be interested in the "Struct", which is part of the IPython package. It does what you want to do, with lots of useful methods.

    http://ipython.org/ipython-doc/rel-0.13/api/generated/IPython.utils.ipstruct.html

    0 讨论(0)
  • 2021-02-01 15:16

    This works in 2.5, 2.6, and 3.1:

    class Struct(object):
        pass
    
    something = Struct()
    something.awesome = abs
    
    result = something.awesome(-42)
    

    EDIT: I thought maybe giving the source would help out as well. http://docs.python.org/tutorial/classes.html#odds-and-ends

    EDIT: Added assignment to result, as I was using the interactive interpreters to verify, and you might not be.

    0 讨论(0)
提交回复
热议问题