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

匆匆过客 提交于 2021-01-27 23:29:14

问题


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


回答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:

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.




回答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.



来源:https://stackoverflow.com/questions/18935882/python-is-it-possible-to-add-new-methods-to-the-tuple-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!