I'm trying to write a wrapper for Python's tuple class, just so I can have an object that behaves like a tuple, but just has a couple of attributes and an extra function or two. I can't seem to resolve the conflict of constructors and inheritance though. This is what I want for the constructor:
class Edge(tuple):
def __init__(self, x, y):
super().__init__(self, (x, y))
self.head, self.tail = x, y
Thus, Edge(1,2)
would form the tuple (1, 2)
with attributes x
and y
. And if it's possible, I'd like to even disallow the tuple's other constructors (tuple()
and tuple(iter)
), but that isn't a priority.
No matter how I write the code, however, it always seems like tuple's constructors take precidence over mine, thus the error: TypeError: tuple() takes at most 1 argument (2 given)
.
I'm using Python 3, which I believe makes a difference in the super()
syntax (I think Python 2 would require something like super(Edge, self).__init__()
).
Edit: For future readers, I solved this with -
class Edge(tuple):
def __new__(cls, x, y):
return super().__new__(cls, (x, y))
def __init__(self, x, y):
super().__init__()
self.head, self.tail = x, y
Edge(1, 2)