2

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)  
Nick
  • 53
  • 7
  • 3
    You might want to take a look at http://stackoverflow.com/q/1565374/2003420 – El Bert Jan 28 '15 at 19:47
  • https://docs.python.org/2/library/functions.html#tuple `tuple`'s constructor takes exactly one argument, an iterable – Jasper Jan 28 '15 at 19:47
  • You may want to look at [`collections.namedtuple()`](https://docs.python.org/3/library/collections.html#collections.namedtuple) instead; `Edge = namedtuple('Edge', 'head tail')`, then `Edge(1, 2)` to create an instance. It'll have `head` and `tail` attributes. – Martijn Pieters Jan 28 '15 at 19:55

0 Answers0