Menu
Coddy logo textTech

ドキュメンテーション文字列

Coddyの「Clean Code - Pythonでより良いコードを書く」コースのレッスン 8/28。

ドキュメント文字列(Docstring)は、通常、モジュール、関数、クラス、またはメソッド定義の最初の文として記述されます。

文字列を"""または'''で囲んでdocstringを宣言します。例えば、

def complex(real=0.0, imag=0.0):
	"""
	複素数を形成する。
	
		Parameters:
			real (float) -- 実部 (デフォルト 0.0)
			imag (float) -- 虚部 (デフォルト 0.0)
	"""
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...

complex(real, imag)関数がどのようにドキュメント化されているか見てみましょう。 

doc本体のインデントと"""に注目してください。

このようにdocstringを使用すると、__doc__プロパティを使ってドキュメントを取得できます。

complex.__doc__

次のように出力されます。

Form a complex number.
	
	Parameters:
		real (float) -- the real part (default 0.0)
		imag (float) -- the imaginary part (default 0.0)
challenge icon

チャレンジ

簡単

docstring の代わりにブロックコメントが付いた関数が与えられます。

あなたの課題は、それを有効な docstring に置き換えることです。正しい docstring の書式にするために、テストケースを確認してください!

自分で試してみよう

def sum_binary(a, b):
    # Calculate sum of two integers in binary formmated string
    # Parameters:
    # a (int) -- Integer number
    # b (int) -- Another integer number
    # Returns:
    # binary_sum (str) -- The sum of a and b in binary format
    sum = a + b
    binary_sum = bin(sum)
    return str(binary_sum)[1:] # Final formmating

print(sum_binary.__doc__)

Clean Code - Pythonでより良いコードを書くのすべてのレッスン

自分で練習してみよう: Pythonオンラインコンパイラ