user1797036
user1797036

Reputation: 71

Python: Is it possible to add new methods to the Tuple class

In Python, is it possible to add new methods to built-in classes, such as Tuple. I'd like to add 2 new methods: first() returns the first element of a tuple, and second() returns a new tuple without the first element.

So for example:

x = (1, 2, 3)

x.first()   # 1
x.second()  # (2, 3)

Thanks

Upvotes: 3

Views: 532

Answers (2)

Veedrac
Veedrac

Reputation: 60217

Yes, but don't.

There exists a dark and dangerous forbiddenfruit that unsafely and dangerously allows such a thing. But it's a dark place to go.

Rather, you can make a new class:

class MyTuple(tuple):
    def first(self):
        return self[0]

    def second(self):
        return self[1:]

mt = MyTuple((1, 2, 3, 4))

mt.first()
#>>> 1
mt.second()
#>>> (2, 3, 4)

Preferably you can create an actual linked list that doesn't require copying every time you call this.

Preferably, don't do that either because there are almost no circumstances at all to want a self-implemented or singly-linked-list in Python.

Upvotes: 5

Marcin
Marcin

Reputation: 49886

No. You could use a namedtuple to introduce names for various positions; or you could subclass tuple; or you could simply write functions. There's nothing wrong with a function.

However, absolutely none of these are a good idea. The best idea is just to write code like everyone else: use subscripts and slices. These are entirely clear, and known to everyone.

Finally, your names are highly misleading: first returns the first element; second returns a tuple composed of the second and third elements.

Upvotes: 3

Related Questions