Python中dir()與help()的使用


python內置了很多內置函數、類方法屬性及各種模塊。當我們想要當我們想要了解某種類型有哪些屬性方法以及每種方法該怎么使用時,我們可以使用dir()函數和help()函數在python ide交互式模式下獲得我們想要的信息。

dir()

dir()用來查詢一個類或者對象所有屬性,比如:

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>

help()

help()函數幫助我們了解模塊、類型、對象、方法、屬性的詳細信息

1.幫助查看類型詳細信息,包含類的創建方式、屬性、方法

>>> help(list)
Help on class list in module builtins:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |
 |  __gt__(self, value, /)
 |      Return self>value.
 |
 |  __iadd__(self, value, /)
 |      Implement self+=value.
 |
 |  __imul__(self, value, /)
 |      Implement self*=value.
 |
 |  __init__(self, /, *args, **kwargs)
-- More  --

2.幫助查看方法的詳細使用信息(使用時要注意輸入完整路徑,使用模塊幫助時,需要先導入模塊)

>>> from selenium.webdriver.common.by import By
>>> help(By)
Help on class By in module selenium.webdriver.common.by:

class By(builtins.object)
 |  Set of supported locator strategies.
 |
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)
 |
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |
 |  CLASS_NAME = 'class name'
 |
 |  CSS_SELECTOR = 'css selector'
 |
 |  ID = 'id'
 |
 |  LINK_TEXT = 'link text'
 |
 |  NAME = 'name'
 |
 |  PARTIAL_LINK_TEXT = 'partial link text'
 |
 |  TAG_NAME = 'tag name'
 |
 |  XPATH = 'xpath'

>>>

 3.舉例如下:

查看python所有的關鍵字:help("keywords")

查看python所有的modules:help("modules")

單看python所有的modules中包含指定字符串的modules: help("modules yourstr")

查看python中常見的topics: help("topics")

查看python標准庫中的module:import os.path + help("os.path")

查看python內置的類型:help("list")

查看python類型的成員方法:help("str.find") 

查看python內置函數:help("open")


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM