python - 我不应该使用内置的元组特定函数吗?
问题描述
当我在网上查找内置集合类型元组 的方法时,它说元组只有两种方法:和。但是,每当我尝试在 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 是正确的。元组不是模块。
解决方案
W3Schools 是一个非常可疑的信息来源,因为它们经常是错误的、误导性的或不完整的。使用官方文档作为您的主要信息来源。
元组实现了常见的序列操作。定义为“序列”的所有内容都支持某些操作,
count
并且index
是其中的两个。其余的序列操作不是作为具体的方法来实现的,而是通过操作符来实现的。例如,将两个序列相加:(1, 2) + (3, 4)
这是通过方法
tuple
在类中实现的。这就是所有运算符与 Python 中的值交互的方式:被翻译成. 这样,每个对象都可以自定义将其“添加”到另一个对象的确切含义。您应该始终使用运算符来使用这些抽象定义,而不是自己调用特定方法。__add__
a + b
a.__add__(b)
__add__
是的,元组是不可变的,所以你不能扩展现有的元组,你只能将两个元组一起添加到一个新的元组中。
推荐阅读
- django - 无法访问远程 vps 上的 django 开发服务器
- java - 在输出前留下特定的间隙
- computer-vision - Pytorch 张量维数乘法
- javascript - 如何为自制的网络服务器获取 SSL 证书
- python - Python中使用`==`比较浮点数的容忍度
- typescript - 如何在 GitHub 上使用 (pro)bot 编辑文件?
- assembly - 使用 8 位寄存器将两个 32 位数字相加
- python - 如何从熊猫系列中选择性地删除字符串?
- python - 如何在熊猫中将标头转换为多标头?这是一个重点问题
- python - 以度数为单位的预处理值以进行回归以避免不连续性