字符串——获得帮助 | 第二部分 类型与操作 —— 第 4 章: 介绍 python 对象类型 |《学习 python:强大的面向对象编程(第 5 版)》| python 技术论坛-江南app体育官方入口
在前一节中介绍的方法是字符串对象中可用方法中的具有代表性的,但很小的样本。一般来说,本书在讲解对象方法时并不是很详尽。要获取更多细节,总是可以调用内置的dir
函数。当不带参数调用时,这个函数列出了在调用者的变量作用域中被赋值的变量;更有用的是,它对任何传递给自己的对象返回了所有可用属性的一个列表。因为方法是函数属性,它们将出现在这个列表中。假设 s
仍然是字符串,下面是python3.10中它的属性(python 2.x 稍有不同):
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
直到本书后面学习类中的操作符重载前,都不用关心在这个列表中带双下划线的名字——它们代表了字符串对象的实现并且可以用来支持自定义。比如,字符串的 __add__
方法是真正用来执行连结的方法;python在内部将下面的第一个语句映射到第二个,然而通常不应该使用第二个形式(它更不直观,而且可能运行得更慢):
>>> s 'ni!'
'spamni!'
>>> s.__add__('ni!')
'spamni!'
通常前导和结尾的双下划线是python用来实现细节的命名模式。在这个列表中没有下划线的名字是字符串对象上可以调用的方法。
dir
函数只是给出了方法名称。要询问它们做什么,可以将它们传递给help
函数:
>>> help(s.replace)
help on built-in function replace:
replace(old, new, count=-1, /) method of builtins.str instance
return a copy with all occurrences of substring old replaced by new.
count
maximum number of occurrences to replace.
-1 (the default value) means replace all occurrences.
if the optional argument count is given, only the first count occurrences are
replaced.
help
是与python一起发布的被称为pydoc(一个用来从对象中提取文档的工具)的代码系统的几个接口之一。在本书稍后将看到pydoc也可以用html格式渲染它的报告并在web浏览器上显示。
还可以对整个字符串询问帮助(比如,help(s)
),但可能得到比想要看到的更多或更少的帮助——在较老版本的python中会有每个字符串方法的信息,而在较新版本中可能根本就不会有帮助信息,因为字符串被特殊处理了。最好是询问一个特定的方法。
>>> help(s)
no python documentation found for 'spam'.
use help() to get the interactive help utility.
use help(str) for help on the str class.
dir
和 help
都将一个真的对象(如我们的字符串s
)或一个数据类型的名称(如 str
,list
,dict
)作为参数。后一个形式(数据类型的名称)对 dir
返回同样的列表,但对 help
显示完整类型的细节,而且允许通过类型名称询问一个特定方法(比如,关于 str.replace
的帮助)。
要获取更多细节,还可以查阅python的标准库参考手册或商业化出版的参考书,但 dir
和 help
是python中第一层级的文档。