Suppose I have a namedtuple like this:
EdgeBase = namedtuple("EdgeBase", "left, right")
I want to implement a custom hash-function for this, so I create the following subclass:
class Edge(EdgeBase):
def __hash__(self):
return hash(self.left) * hash(self.right)
Since the object is immutable, I want the hash-value to be calculated only once, so I do this:
class Edge(EdgeBase):
def __init__(self, left, right):
self._hash = hash(self.left) * hash(self.right)
def __hash__(self):
return self._hash
This appears to be working, but I am really not sure about subclassing and initialization in Python, especially with tuples. Are there any pitfalls to this solution? Is there a recommended way how to do this? Is it fine? Thanks in advance.
edit for 2017: turns out
namedtupleisn’t a great idea. attrs is the modern alternative.__new__is what you want to call here because tuples are immutable. Immutable objects are created in__new__and then returned to the user, instead of being populated with data in__init__.clshas to be passed twice to thesupercall on__new__because__new__is, for historical/odd reasons implicitly astaticmethod.