python 怎么看某個(gè)包里面有哪些變量、方法、函數(shù)和類

Python?dir() 函數(shù)用來(lái)列出某個(gè)類或者某個(gè)模塊中的全部?jī)?nèi)容,包括變量、方法、函數(shù)和類等,它的用法為:
dir(obj)
obj 表示要查看的對(duì)象。obj 可以不寫(xiě),此時(shí) dir()?會(huì)列出當(dāng)前范圍內(nèi)的變量、方法和定義的類型。
Python help() 函數(shù)用來(lái)查看某個(gè)函數(shù)或者模塊的幫助文檔,它的用法為:
help(obj)
obj 表示要查看的對(duì)象。obj 可以不寫(xiě),此時(shí) help() 會(huì)進(jìn)入幫助子程序。
命令執(zhí)行之后執(zhí)行后,會(huì)列出NAME(模塊名)、PACKAGE CONTENTS(包內(nèi)容)、FUNCTIONS(函數(shù))、DATA(數(shù)據(jù))、VERSION(版本號(hào))、FILE(文件,包含了目錄)。

掌握了以上兩個(gè)函數(shù),我們就可以自行查閱 Python 中所有方法、函數(shù)、變量、類的用法和功能了。
【實(shí)例】使用 dir() 查看字符串類型(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', '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']
在 Python 標(biāo)準(zhǔn)庫(kù)中,以__
開(kāi)頭和結(jié)尾的方法都是私有的,不能在類的外部調(diào)用。
【實(shí)例】使用 help() 查看 str 類型中 lower() 函數(shù)的用法:
>>> help(str.lower)
Help on method_descriptor:
lower(self, /)
??? Return a copy of the string converted to lowercase.
可以看到,lower() 函數(shù)用來(lái)將字符串中的字母轉(zhuǎn)換為小寫(xiě)形式,并返回一個(gè)新的字符串。
注意,使用 help() 查看某個(gè)函數(shù)的用法時(shí),函數(shù)名后邊不能帶括號(hào),例如將上面的命令寫(xiě)作help(str.lower())
就是錯(cuò)誤的。