文件撰寫

Python 的軟體工程原則

Adam Spannbauer

Machine Learning Engineer at Eastman

Python 中的文件撰寫

  • 註解
# Square the number x
  • 文件字串(docstring)
    """Square the number x

    :param x: number to square
    :return: x squared

    >>> square(2)
    4
    """
Python 的軟體工程原則

註解

# This is a valid comment
x = 2
y = 3  # This is also a valid comment
# You can't see me unless you look at the source code

# Hi future collaborators!!
Python 的軟體工程原則

有效的註解

標註「做了什麼」

# Define people as 5
people = 5

# Multiply people by 3
people * 3

標註「為什麼這樣做」

# There will be 5 people attending the party
people = 5

# We need 3 pieces of pizza per person
people * 3
Python 的軟體工程原則

文件字串(docstring)

def function(x):
    """High level description of function

    Additional details on function
Python 的軟體工程原則

文件字串(docstring)

def function(x):
    """High level description of function

    Additional details on function

    :param x: description of parameter x
    :return: description of return value

從 Flask 套件的 docstring 產生的範例網頁.

Python 的軟體工程原則

文件字串(docstring)

def function(x):
    """High level description of function

    Additional details on function

    :param x: description of parameter x
    :return: description of return value

    >>> # Example function usage
    Expected output of example function usage
    """
    # function code
Python 的軟體工程原則

文件字串範例

def square(x):
    """Square the number x

    :param x: number to square
    :return: x squared

    >>> square(2)
    4
    """
    # `x * x` is faster than `x ** 2`
    # reference: https://stackoverflow.com/a/29055266/5731525
    return x * x
Python 的軟體工程原則

文件字串輸出範例

help(square)
square(x)
    Square the number x

    :param x: number to square
    :return: x squared

    >>> square(2)
    4
Python 的軟體工程原則

一起來練習吧!

Python 的軟體工程原則

Preparing Video For Download...