我不应该使用内置的元组特定函数吗?

问题描述

当我查找内置集合类型 tuple online方法时,它说元组只有两个方法count()index() .但是,每当我尝试在 pydoc 中查找元组时:

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,/)
 |      Return self==value.
 |
 |  __ge__(self,/)
 |      Return self>=value.
 |
 |  __getattribute__(self,name,/)
 |      Return getattr(self,name).
 |
 |  __getitem__(self,/)
 |      Return self[key].
 |

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

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

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

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

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

解决方法

  1. W3Schools 是一个非常有问题的信息来源,因为它们经常是错误的、误导性的或不完整的。使用 official documentation 作为您的主要信息来源。

  2. 元组实现了 common sequence operations。定义为“sequence”的所有内容都支持某些操作,countindex 就是其中的两个。其余的序列操作不是作为特定方法实现的,而是通过运算符实现的。例如,将两个序列相加:

    (1,2) + (3,4)
    

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

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

,

pydoc 提到的方法,以双下划线开头和结尾。这些用于实现运算符、内置方法等。应该很少调用。

From the Python PEP 8 -- Style Guide for Python Code

Descriptive: Naming Styles

  • double_leading_and_trailing_underscore_:存在于用户控制的命名空间中的“神奇”对象或属性。例如。 initimportfile。永远不要发明这样的名字;仅按照文档使用它们。

而且 w3schools 不是一个好的参考,请务必查看 Python 文档。例如 - Tuples