python如何查看类的函数

Python非常方便,它不需要用户查询文档,只需掌握如下两个帮助函数,即可查看Python中的所有函数(方法)以及它们的用法和功能:

dir():列出指定类或模块包含的全部内容(包括函数、方法、类、变量等)。

help():查看某个函数或方法的帮助文档。

例如,要查看字符串变量(它的类型是 str 类型)所能调用的全部内容,可以在交互式解释器中输入如下命令:

复制代码
>>> dir(str)
['__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', '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)提供的所有方法,其中以""开头、""结尾的方法被约定成私有方法,不希望被外部直接调用。

如果希望查看某个方法的用法,则可使用 help() 函数。例如,在交互式解释器中输入如下命令:

复制代码
>>> help(str.title)
Help on method_descriptor:
title(...)
    S.title() -> str
   
    Return a titlecased version of S, i.e. words start with title case
    characters, all remaining cased characters have lower case.
>>>

从上面介绍可以看出,title()方法的使用形式是"str.title()",其功能是将字符串中所有单词的首字母大写,其他所有字符全部改为小写。

通过使用 dir() 和 help() 函数,我们就可以查看字符串变量所能调用的所有方法,包括他们的使用方法和功能等。

相关推荐
初阳7852 分钟前
【Qt】系统相关(2)——文件
开发语言·qt
江华森6 分钟前
Python 编程快速上手:让繁琐工作自动化 —— 19章全实战笔记
笔记·python·自动化
子豪-中国机器人11 分钟前
第一部分:初赛选择题(30 题,对应线上每日问答)
python
Sam092711 分钟前
【AI 算法精讲 15】余弦相似度:向量检索与归一化内积
人工智能·python·算法·ai
Starry-sky(jing)35 分钟前
RecursionError: maximum recursion depth exceeded —— 你的函数调用链,踩穿了 CPython 的安全气囊
python·cpython·pydantic·recursionerror·递归深度·递归限制·sys.setrecursionlimit
Ricky_Theseus37 分钟前
Trie 字典树:前缀匹配利器
开发语言·c#
cui_ruicheng39 分钟前
Python从入门到实战(三):流程控制与循环语句
开发语言·python
Rauser Mack1 小时前
Vibe coding游戏实战:零代码编程五子棋小游戏
人工智能·python·游戏·html·prompt
zh_xuan1 小时前
c++ std::Any 用法
开发语言·c++·any
小杍随笔1 小时前
【Rust全栈项目接入UUID主键实战:从选型到PostgreSQL适配(含v7优化)】
开发语言·postgresql·rust