首页 > 解决方案 > 我不应该使用内置的元组特定函数吗?

问题描述

当我在网上查找内置集合类型元组 的方法时,它说元组只有两种方法:和。但是,每当我尝试在 pydoc 中查找元组时:count()index()

python -m pydoc tuple

我得到以下信息:

Help on class tuple in module builtins:

class tuple(object)
 |  tuple(iterable=(), /)
 |
 |  Built-in immutable sequence.
 |
 |  If no argument is given, the constructor returns an empty tuple.
 |  If iterable is specified the tuple is initialized from iterable's items.
 |
 |  If the argument is a tuple, the return value is the same object.
 |
 |  Built-in subclasses:
 |      asyncgen_hooks
 |      UnraisableHookArgs
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __getitem__(self, key, /)
 |      Return self[key].
 |

它持续了一段时间。我注意到如果我想向元组添加一个元素,那么我必须创建一个新元组。

a = ('hi', 'my')
b = (*a, 'name', 'is')
>>> b
('hi', 'my', 'name', 'is')

但是方法add () 对我做同样的事情。

pydocs 中弹出的方法是否是不打算在模块外部使用的特定于模块的方法?我想有点像封装的弱形式?

编辑:从标题中取出“模块”。@juanpa.arrivillaga 是正确的。元组不是模块。

标签: pythonpython-3.xtuplesmagic-methods

解决方案


  1. W3Schools 是一个非常可疑的信息来源,因为它们经常是错误的、误导性的或不完整的。使用官方文档作为您的主要信息来源。

  2. 元组实现了常见的序列操作。定义为“序列”的所有内容都支持某些操作,count并且index是其中的两个。其余的序列操作不是作为具体的方法来实现的,而是通过操作符来实现的。例如,将两个序列相加:

    (1, 2) + (3, 4)
    

    这是通过方法tuple在类中实现的。这就是所有运算符与 Python 中的值交互的方式:被翻译成. 这样,每个对象都可以自定义将其“添加”到另一个对象的确切含义。您应该始终使用运算符来使用这些抽象定义,而不是自己调用特定方法。__add__a + ba.__add__(b)__add__

    是的,元组是不可变的,所以你不能扩展现有的元组,你只能将两个元组一起添加到一个新的元组中。


推荐阅读