Existence of mutable named tuple in Python?

前端 未结 10 2177
旧巷少年郎
旧巷少年郎 2020-11-29 16:23

Can anyone amend namedtuple or provide an alternative class so that it works for mutable objects?

Primarily for readability, I would like something similar to namedt

10条回答
  •  猫巷女王i
    2020-11-29 17:00

    Tuples are by definition immutable.

    You can however make a dictionary subclass where you can access the attributes with dot-notation;

    In [1]: %cpaste
    Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
    :class AttrDict(dict):
    :
    :    def __getattr__(self, name):
    :        return self[name]
    :
    :    def __setattr__(self, name, value):
    :        self[name] = value
    :--
    
    In [2]: test = AttrDict()
    
    In [3]: test.a = 1
    
    In [4]: test.b = True
    
    In [5]: test
    Out[5]: {'a': 1, 'b': True}
    

提交回复
热议问题