简体   繁体   English

Python:是否可以向Tuple类添加新方法

[英]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. 在Python中,可以向内置类(例如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. 我想添加2个新方法:first()返回元组的第一个元素,second()返回不包含第一个元素的新元组。

So for example: 因此,例如:

x = (1, 2, 3)

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

Thanks 谢谢

No. You could use a namedtuple to introduce names for various positions; namedtuple 。您可以使用namedtuple为各个职位介绍姓名; 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. 第二个返回由第二个和第三个元素组成的元组。

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. 最好不要这样做,因为几乎没有任何情况希望在Python中使用自实现列表或单链接列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM