字符串——获得帮助

未匹配的标注

在前一节中介绍的方法是字符串对象中可用方法中的具有代表性的,但很小的样本。一般来说,本书在讲解对象方法时并不是很详尽。要获取更多细节,总是可以调用内置的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.

dirhelp 都将一个真的对象(如我们的字符串S)或一个数据类型的名称(如 strlistdict)作为参数。后一个形式(数据类型的名称)对 dir 返回同样的列表,但对 help 显示完整类型的细节,而且允许通过类型名称询问一个特定方法(比如,关于 str.replace 的帮助)。

要获取更多细节,还可以查阅Python的标准库参考手册或商业化出版的参考书,但 dirhelp 是Python中第一层级的文档。

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~