Menu
Coddy logo textTech

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

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

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

Docstringを宣言するには、文字列を"""または'''で囲みます。例えば、

def complex(real=0.0, imag=0.0):
	"""
	Form a complex number.
	
		Parameters:
			real (float) -- the real part (default 0.0)
			imag (float) -- the imaginary part (default 0.0)
	"""
    if imag == 0.0 and real == 0.0:
        return complex_zero
    ...

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

ドキュメント本体と"""のインデントに注目してください。

このように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)の代わりにブロックコメントが含まれている関数が与えられます。

あなたのタスクは、それを有効なドキュメント文字列に置き換えることです。正しいフォーマットにするためにテストケースを確認してください!

自分で試してみよう

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でより良いコードを書くのすべてのレッスン