Python: Is It Possible To Add New Methods To The Tuple Class
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"