How to provide additional initialization for a subclass of namedtuple?

前端 未结 3 2056
太阳男子
太阳男子 2020-12-23 17:25

Suppose I have a namedtuple like this:

EdgeBase = namedtuple(\"EdgeBase\", \"left, right\")

I want to implement a custom hash-

3条回答
  •  醉话见心
    2020-12-23 17:55

    The code in the question could benefit from a super call in the __init__ in case it ever gets subclassed in a multiple inheritance situation, but otherwise is correct.

    class Edge(EdgeBase):
        def __init__(self, left, right):
            super(Edge, self).__init__(left, right)
            self._hash = hash(self.left) * hash(self.right)
    
        def __hash__(self):
            return self._hash
    

    While tuples are readonly only the tuple parts of their subclasses are readonly, other properties may be written as usual which is what allows the assignment to _hash regardless of whether it's done in __init__ or __new__. You can make the subclass fully readonly by setting it's __slots__ to (), which has the added benefit of saving memory, but then you wouldn't be able to assign to _hash.

提交回复
热议问题