python的help()、dir()演示

当你遇到一个不会的函数时,如何去查找它呢。py编译器中,可以通过一些函数来获取官方提供的文档,在本期,我们演示一下这些函数将如何使用。

1.dir()函数

这是py的一个内置函数,可以返回()内所有属性的名称,以列表的形式。

这里拿str举例,str是python的数据类型之一,又叫字符串。

现在我们进入python的交互模式,并输入:dir(str),回车。注意括号是英文下的。

1 >>> dir(str)
2 ['__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', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

你会看到所有和str有关的函数。那么如何查看str的某个属性的功能呢?这里就需要用到py的另一个函数help()了。

2.help()函数

假如你现在电脑旁放着一本书,如果用这本书来做比喻的话,dir()就相当于书的目录,而help()就是除了目录外的所有内容了。现在输入:help(str),让我们看看str中都有什么,你会发现它像书一样的整齐和悦目。

 1 >>> help(str)
 2 Help on class str in module builtins:    ;; 以下是类str的文档
 3 
 4 class str(object)
 5  |  str(object='') -> str
 6  |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 7  |  
 8  |  Create a new string object from the given object. If encoding or
 9  |  errors is specified, then the object must expose a data buffer
10  |  that will be decoded using the given encoding and error handler.
11  |  Otherwise, returns the result of object.__str__() (if defined)
12  |  or repr(object).
13  |  encoding defaults to sys.getdefaultencoding().
14  |  errors defaults to 'strict'.

因为str的文档有很多,我在这里简要的发出其中的三段来。分别是开头,以下划线开头的函数,以及以字母开头的函数。你可以在自己的电脑里看全部的文档。

 1  |  Methods defined here:
 2  |  
 3  |  __add__(self, value, /)   ;; __add__函数,()括号内是它的参数,具体用法如下演示
 4  |      Return self+value.    ;; 该函数的功能
 5  |  
 6  |  __contains__(self, key, /)
 7  |      Return key in self.
 8  |  
 9  |  __eq__(self, value, /)
10  |      Return self==value.
11  |  
12  |  __format__(self, format_spec, /)
13  |      Return a formatted version of the string as described by format_spec.

以下划线开头的函数,如何使用呢?可以通过下面的例子对照上面看。

 1 >>> name = "Jake"    ;; 命名了一个名叫name的字符串,内容是Jake
 2 
 3 >>> name.__add__("is good!") ;; "Jake" + "is good",并形成一个新字符串,这里演示的是__add__的用法
 4 'Jakeis good!'
 5 >>> name                     ;; 原字符串不变
 6 'Jake'
1 >>> name.__contains__("Ja")  ;; 判断()是否是字符串name中的一部分,返回True或False,函数__contains__的用法
2 True
3 >>> name.__contains__("po")
4 False
5 
6 >>> name.__eq__("dddd")      ;; 判断()内字符是否与name相等,函数__eq__的用法
7 False
8 >>> name.__eq__("Jake")
9 True

接下来是以字母开头的函数。

 1  |  
 2  |  capitalize(self, /)                              ;; 函数名称及参数
 3  |      Return a capitalized version of the string.  ;; 功能
 4  |  
 5  |      More specifically, make the first character have upper case and the rest lower
 6  |      case.
 7  |  
 8  |  casefold(self, /)
 9  |      Return a version of the string suitable for caseless comparisons.
10  |  
11  |  center(self, width, fillchar=' ', /)
12  |      Return a centered string of length width.
13  |      
14  |      Padding is done using the specified fill character (default is a space).
15  |  
16  |  count(...)
17  |      S.count(sub[, start[, end]]) -> int
18  |      
19  |      Return the number of non-overlapping occurrences of substring sub in
20  |      string S[start:end].  Optional arguments start and end are
21  |      interpreted as in slice notation.

演示:

 1 >>> a = 'my name is Jake'    ;; 创建名字为a的字符串
 2 
 3 >>> a.capitalize()           ;; 将首字母大写,其余小写
 4 'My name is jake'
 5 
 6 >>> a.casefold()             ;; 所有字母小写
 7 'my name is jake'
 8 
 9 >>> a.center(20)             ;; 该函数有两个参数,第一个为宽度,第二个为填充物,默认为空格
10 '  my name is Jake   '       ;; 这里的宽度为20,多余的地方用空格表示
11 >>> a.center(20, '_')        ;; 设置填充物为下划线
12 '__my name is Jake___'
13 
14 >>> name = 'JakeJake'        
15 >>> name.count('a')          ;; count用于搜索name中有多少个(),并返回数量
16 2
17 >>> name.count('a', 0, 5)    ;; 共有3个参数,第一个是搜索的对象,第二个是开始,第三个是结尾
18 1

3.组合使用

当你不清楚一个数据类型都有哪些属性时,可以通过str()来看看它的目录。比如我输入了dir(str),就会看到str的函数名称列表。

我需要列表中的__add__函数的功能介绍,你可以通过输入:help(str.__add__)

1 >>> help(str.__add__)
2 Help on wrapper_descriptor:
3 
4 __add__(self, value, /)
5     Return self+value.

这样就能找到该函数的介绍了,是不是很方便呢。

什么?你不知道help(str.__add__)中的英文标点‘ . ’是什么意思?看一下这个链接,或许你可以明白:https://www.zhihu.com/question/64637633

猜你喜欢

转载自www.cnblogs.com/nianqiantuling/p/9020772.html