Python:是否可以向 Tuple 类添加新方法 [英] Python: Is it possible to add new methods to the Tuple class

查看:27
本文介绍了Python:是否可以向 Tuple 类添加新方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,是否可以向内置类添加新方法,例如 Tuple.我想添加 2 个新方法:first() 返回元组的第一个元素,而 second() 返回一个没有第一个元素的新元组.

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.

例如:

x = (1, 2, 3)

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

谢谢

推荐答案

,但不要.

存在一个黑暗和危险的禁果,它不安全且危险地允许这样的事情发生.但这是一个黑暗的地方.

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.

最好不要这样做,因为几乎没有任何情况需要 Python 中的自实现或单链表.

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.

这篇关于Python:是否可以向 Tuple 类添加新方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆