Python基礎(09):幫助

Ryan_Bai發表於2019-02-18

一、註釋

確保對模組, 函式, 方法和行內註釋使用正確的風格

  1. 單行註釋以 # 開頭

    # 這是一個註釋
    print("Hello, World!")
    
  2. 單引號(''')

    #!/usr/bin/python3
    '''
    這是多行註釋,用三個單引號
    這是多行註釋,用三個單引號
    這是多行註釋,用三個單引號
    '''
    print("Hello, World!")
    
  3. 雙引號(""")

    #!/usr/bin/python3
    """
    這是多行註釋,用三個單引號
    這是多行註釋,用三個單引號
    這是多行註釋,用三個單引號
    """
    print("Hello, World!")
    

二、DIR

  • 語法:dir([object])

  • 說明:

    • 當不傳引數時,返回當前作用域內的變數、方法和定義的型別列表。

      >>> dir()
      ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
      >>> a = 10 #定義變數a
      >>> dir() #多了一個a
      ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a']
      
    • 當引數物件是模組時,返回模組的屬性、方法列表。

      >>> import math
      >>> math
      <module 'math' (built-in)>
      >>> dir(math)
      ['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
      
    • 當引數物件是類時,返回類及其子類的屬性、方法列表。

      >>> class A:
          name = 'class'
      >>> a = A()
      >>> dir(a) #name是類A的屬性,其他則是預設繼承的object的屬性、方法
      ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']
      
    • 當物件定義了__dir__方法,則返回__dir__方法的結果

      >>> class B:
          def __dir__(self):
              return ['name','age']
      >>> b = B()
      >>> dir(b) #呼叫 __dir__方法
      ['age', 'name']
      

三、__doc__

將文件寫在程式裡,是LISP中的一個特色,Python也借鑑過。每個函式都是一個物件,每個函式物件都是有一個__doc__的屬性,函式語句中,如果第一個表示式是一個string,這個函式的__doc__就是這個string,否則__doc__是None。

>>> def testfun():
"""
this function do nothing , just demostrate the use of the doc string .
"""
pass
>>> testfun.__doc__
'\nthis function do nothing , just demostrate the use of the doc string .\n'
>>> #pass 語句是空語句,什麼也不幹,就像C語言中的{} , 透過顯示__doc__,我們可以檢視一些內部函式的幫助資訊
>>> " ".join.__doc__
'S.join(iterable) -> str\n\nReturn a string which is the concatenation of the strings in the\niterable. The separator between elements is S.'
>>>

四、help

  • 語法:help([object])

  • 說明:

    • 在直譯器互動介面,不傳引數呼叫函式時,將啟用內建的幫助系統,並進入幫助系統。在幫助系統內部輸入模組、類、函式等名稱時,將顯示其使用說明,輸入quit退出內建幫助系統,並返回互動介面。

      >>> help() #不帶引數
       
      Welcome to Python 3.5's help utility!
      If this is your first time using Python, you should definitely check out
      the tutorial on the Internet at 
       
      Enter the name of any module, keyword, or topic to get help on writing
      Python programs and using Python modules.  To quit this help utility and
      return to the interpreter, just type "quit".
       
      To get a list of available modules, keywords, symbols, or topics, type
      "modules", "keywords", "symbols", or "topics".  Each module also comes
      with a one-line summary of what it does; to list the modules whose name
      or summary contain a given string such as "spam", type "modules spam".
       
      #進入內建幫助系統  >>> 變成了 help>
      help> str #str的幫助資訊
      Help on class str in module builtins:
       
      class str(object)
      |  str(object='') -> str
      |  str(bytes_or_buffer[, encoding[, errors]]) -> str
      |
      |  Create a new string object from the given object. If encoding or
      |  errors is specified, then the object must expose a data buffer
      |  that will be decoded using the given encoding and error handler.
      |  Otherwise, returns the result of object.__str__() (if defined)
      |  or repr(object).
      |  encoding defaults to sys.getdefaultencoding().
      |  errors defaults to 'strict'.
      |
      |  Methods defined here:
      |
      |  __add__(self, value, /)
      |      Return self+value.
      ................................
       
      help> 1 #不存在的模組名、類名、函式名
      No Python documentation found for '1'.
      Use help() to get the interactive help utility.
      Use help(str) for help on the str class.
       
      help> quit #退出內建幫助系統
       
      You are now leaving help and returning to the Python interpreter.
      If you want to ask for help on a particular object directly from the
      interpreter, you can type "help(object)".  Executing "help('string')"
      has the same effect as typing a particular string at the help> prompt.
       
      # 已退出內建幫助系統,返回互動介面 help> 變成 >>>
      
    • 在直譯器互動介面,傳入引數呼叫函式時,將查詢引數是否是模組名、類名、函式名,如果是將顯示其使用說明。

      >>> help(str)
      Help on class str in module builtins:
       
      class str(object)
      |  str(object='') -> str
      |  str(bytes_or_buffer[, encoding[, errors]]) -> str
      |
      |  Create a new string object from the given object. If encoding or
      |  errors is specified, then the object must expose a data buffer
      |  that will be decoded using the given encoding and error handler.
      |  Otherwise, returns the result of object.__str__() (if defined)
      |  or repr(object).
      |  encoding defaults to sys.getdefaultencoding().
      |  errors defaults to 'strict'.
      |
      |  Methods defined here:
      |
      |  __add__(self, value, /)
      |      Return self+value.
      |
        ***************************
      

五、標準手冊集


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31490526/viewspace-2636237/,如需轉載,請註明出處,否則將追究法律責任。

相關文章