当我在 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'
