Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

classMyTuple(tuple):deffirst(self):
        returnself[0]

    defsecond(self):
        returnself[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.

Solution 2:

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.

Post a Comment for "Python: Is It Possible To Add New Methods To The Tuple Class"