1. 程式人生 > >Python筆記:文件註釋docstrings, 讓函式更易讀懂

Python筆記:文件註釋docstrings, 讓函式更易讀懂

本筆記整理自 udacity 課程,版權歸 udacity 所有,僅作為學習交流,更多學習資源和資訊請訪問 Udacity

文件 docstrings

  • 文件字串是一種註釋,用於解釋函式的作用以及使用方式,文件字串用三個引號引起來:

    def population_density(population, land_area):
      """Calculate the population density of an area. """
      return population / land_area
  • 一行文件字串完全可接受, 可以在一行摘要後面新增更多資訊。我們還可以對函式的引數進行了解釋,描述每個引數的作用和型別。我們經常還會對函式輸出進行說明:

    def population_density(population, land_area):
      """Calculate the population density of an area.
    
      INPUT:
      population: int. The population of that area
      land_area: int or float. This function is unit-agnostic, if you pass in values in terms
      of square km or square miles the function will return a density in those units.
    
      OUTPUT: 
      population_density: population / land_area. The population density of a particular area.
      """
    return population / land_area