Existence of mutable named tuple in Python?

前端 未结 10 2178
旧巷少年郎
旧巷少年郎 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条回答
  •  甜味超标
    2020-11-29 17:03

    It seems like the answer to this question is no.

    Below is pretty close, but it's not technically mutable. This is creating a new namedtuple() instance with an updated x value:

    Point = namedtuple('Point', ['x', 'y'])
    p = Point(0, 0)
    p = p._replace(x=10) 
    

    On the other hand, you can create a simple class using __slots__ that should work well for frequently updating class instance attributes:

    class Point:
        __slots__ = ['x', 'y']
        def __init__(self, x, y):
            self.x = x
            self.y = y
    

    To add to this answer, I think __slots__ is good use here because it's memory efficient when you create lots of class instances. The only downside is that you can't create new class attributes.

    Here's one relevant thread that illustrates the memory efficiency - Dictionary vs Object - which is more efficient and why?

    The quoted content in the answer of this thread is a very succinct explanation why __slots__ is more memory efficient - Python slots

提交回复
热议问题