Namedtuple like class

后端 未结 5 1918
有刺的猬
有刺的猬 2021-02-06 01:27

I find myself writing this class often in my python code when I need a quick single use class.

class Struct(object):
   def __init__( self, **kwargs ):
      for          


        
5条回答
  •  臣服心动
    2021-02-06 02:05

    From Python 3.3 and afterwards, you can use types.SimpleNamespace:

    >>> import types
    >>> foo = types.SimpleNamespace(bar='one', baz=1)
    >>> print(foo.bar)
    one
    >>> foo.baz += 1
    >>> foo.novo = 42
    

    The builtin type is roughly equivalent to the following code:

    class SimpleNamespace:
    
        def __init__(self, **kwargs):
            self.__dict__.update(kwargs)
    
        def __repr__(self):
            keys = sorted(self.__dict__)
            items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
            return "{}({})".format(type(self).__name__, ", ".join(items))
    
        def __eq__(self, other):
            return self.__dict__ == other.__dict__
    

    update

    Starting with Python 3.7, you can use the dataclass module:

    from dataclasses import dataclass, field
    
    @dataclass
    class Struct:
        bar: str = field(default='one')
        baz: int = field(default=1)
    

    You can use this as follows:

    foo = Struct( bar='one', baz=1 )
    print(foo.bar)
    foo.baz += 1
    foo.novo = 42
    

    By default, it incorporates equality testing and a nice looking repr:

    >>> foo == Struct(bar='one', baz=2)
    True
    >>> foo
    Struct(bar='one', baz=2)
    

提交回复
热议问题