gpt4 book ai didi

python - python help ('string' ) 与 help(list) 不一致?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:57 27 4
gpt4 key购买 nike

当我在 python 解释器中键入 help('string') 时,我得到了有关字符串类的信息。在那里,upper() 被表示为一个函数。然而,我只能将其称为 "hi".upper() 而不是 upper("hi").
因此,可以假设任何方法都将在内置模块的文档字符串中指示为函数。然而,当我执行 help('list') 时,列表类的方法被指示为文档字符串中的方法!!
为什么会这样?仅仅是因为写教义的人不一致还是不同的人写的?还是这些方法(文档字符串中称为“函数”的方法与称为“方法”的方法)实际上具有不同的属性?

最佳答案

当您搜索 help('string') 时,您正在寻找 string 模块 的文档字符串。如果你执行 help(str)help('str') 你会得到 str 类型的文档字符串,这里 upper 作为方法出现!

正如您在这里看到的,string 模块中的函数 upper 实际上是一个函数而不是方法:

>>> upper('hi')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'upper' is not defined
>>> 'hi'.upper() # method from the str type
'HI'
>>> from string import upper
>>> upper('hi') # function from the string module
'HI'

关于python - python help ('string' ) 与 help(list) 不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9998488/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com