Python のドキュメント文字列
クリーンで十分に文書化されたコードを作成する場合、Python 開発者は自由に使える秘密兵器、docstring を持っています。 docstring はドキュメント文字列の略で、目的と機能を伝えるために不可欠です。 パイソン 関数、モジュール、クラス。
Python の docstring とは何ですか?
パイソン ドキュメント文字列 (または docstring) は、ドキュメントを関連付ける便利な方法を提供します。 Pythonモジュール 、関数、クラス、メソッド。これは、コードの特定のセグメントを文書化するためにコメントと同様に使用されるソース コードで指定されます。従来のソース コード コメントとは異なり、docstring は関数がどのように行うかではなく、何を行うかを説明する必要があります。
- docstring の宣言 : docstring は、クラス、メソッド、または関数の宣言のすぐ下で「三重一重引用符」または三重二重引用符を使用して宣言されます。すべての関数には docstring が必要です。
- ドキュメント文字列へのアクセス : docstring には、オブジェクトの __doc__ メソッドまたはヘルプ関数を使用してアクセスできます。以下の例は、docstring を宣言してアクセスする方法を示しています。
docstring はどのようにあるべきでしょうか?
- doc 文字列行は大文字で始まり、ピリオドで終わる必要があります。
- 最初の行は短い説明にする必要があります。
- ドキュメント文字列にさらに多くの行がある場合は、2 行目を空白にし、概要と残りの説明を視覚的に分離する必要があります。
- 次の行は、オブジェクトの呼び出し規則、副作用などを説明する 1 つ以上の段落にする必要があります。
Python のドキュメント文字列
この記事で取り上げるトピックは次のとおりです。
- 三重引用符で囲まれた文字列
- Google スタイルのドキュメント文字列
- Numpydoc スタイルのドキュメント文字列
- 一行のドキュメント文字列
- 複数行のドキュメント文字列
- docstring のインデント
- クラス内の docstring
- Python コメントと docstring の違い
三重引用符で囲まれた文字列
これは、Python で最も一般的な docstring 形式です。これには、三重引用符 (一重または二重) を使用してドキュメントのテキストを囲むことが含まれます。三重引用符で囲まれた文字列は複数行にまたがることがあり、多くの場合、関数、クラス、またはモジュール定義の直下に配置されます。
例 1: 三重一重引用符の使用
Python3
def> my_function():> > '''Demonstrates triple double quotes> > docstrings and does nothing really.'''> > > return> None> print> (> 'Using __doc__:'> )> print> (my_function.__doc__)> print> (> 'Using help:'> )> help> (my_function)> |
出力:
Using __doc__: Demonstrates triple double quotes docstrings and does nothing really. Using help: Help on function my_function in module __main__: my_function() Demonstrates triple double quotes docstrings and does nothing really.
例 2: 三重二重引用符の使用
Python3
def> my_function():> > ' '> 'Demonstrates triple double quotes docstrings and does nothing really'> ' '> > > return> None> print> (> 'Using __doc__:'> )> print> (my_function.__doc__)> print> (> 'Using help:'> )> help> (my_function)> |
出力:
Using __doc__: Demonstrates triple double quotes docstrings and does nothing really. Using help: Help on function my_function in module __main__: my_function() Demonstrates triple double quotes docstrings and does nothing really.
Google スタイルのドキュメント文字列
Google スタイルのドキュメント文字列は特定の形式に従い、Google のドキュメント スタイル ガイドに影響を受けています。これらは、パラメーター、戻り値、説明などの Python コードを文書化するための構造化された方法を提供します。
Python3
def> multiply_numbers(a, b):> > '''> > Multiplies two numbers and returns the result.> > Args:> > a (int): The first number.> > b (int): The second number.> > Returns:> > int: The product of a and b.> > '''> > return> a> *> b> print> (multiply_numbers(> 3> ,> 5> ))> |
出力
15
Numpydoc スタイルのドキュメント文字列
Numpydoc スタイルの docstring は、特に数値計算やデータ操作に関連する関数やクラスを文書化するために、科学およびデータ分析コミュニティで広く使用されています。これは Google スタイルの docstring の拡張であり、パラメータと戻り値を文書化するための追加の規則がいくつかあります。
Python3
def> divide_numbers(a, b):> > '''> > Divide two numbers.> > Parameters> > ----------> > a : float> > The dividend.> > b : float> > The divisor.> > Returns> > -------> > float> > The quotient of the division.> > '''> > if> b> => => 0> :> > raise> ValueError(> 'Division by zero is not allowed.'> )> > return> a> /> b> print> (divide_numbers(> 3> ,> 6> ))> |
出力
0.5
一行のドキュメント文字列
名前が示すように、1 行の docstring は 1 行に収まります。それらは明らかな場合に使用されます。終了引用符は開始引用符と同じ行にあります。これはワンライナーの方が良さそうです。例えば:
Python3
def> power(a, b):> > ' '> 'Returns arg1 raised to power arg2.'> ' '> > > return> a> *> *> b> print> (power.__doc__)> |
出力:
Returns arg1 raised to power arg2.
複数行のドキュメント文字列
複数行の docstring は、1 行の docstring と同様に概要行と、その後に続く空行、さらに詳しい説明で構成されます。要約行は、開始引用符と同じ行または次の行に配置できます。以下の例は、複数行の docstring を示しています。
Python3
def> add_numbers(a, b):> > '''> > This function takes two numbers as input and returns their sum.> > Parameters:> > a (int): The first number.> > b (int): The second number.> > Returns:> > int: The sum of a and b.> > '''> > return> a> +> b> print> (add_numbers(> 3> ,> 5> ))> |
出力:
8
docstring のインデント
docstring 全体は、最初の行の引用符と同じようにインデントされます。 docstring 処理ツールは、docstring の 2 行目以降の行から、最初の行以降のすべての非空白行の最小インデントと同じ量のインデントを均一に取り除きます。 docstring の最初の行 (つまり、最初の新しい行まで) のインデントは重要ではないため、削除されます。 docstring 内の以降の行の相対インデントは保持されます。
Python3
class> Employee:> > '''> > A class representing an employee.> > Attributes:> > name (str): The name of the employee.> > age (int): The age of the employee.> > department (str): The department the employee works in.> > salary (float): The salary of the employee.> > '''> > def> __init__(> self> , name, age, department, salary):> > '''> > Initializes an Employee object.> > Parameters:> > name (str): The name of the employee.> > age (int): The age of the employee.> > department (str): The department the employee works in.> > salary (float): The salary of the employee.> > '''> > self> .name> => name> > self> .age> => age> > self> .department> => department> > self> .salary> => salary> > def> promote(> self> , raise_amount):> > '''> > Promotes the employee and increases their salary.> > Parameters:> > raise_amount (float): The raise amount to increase the salary.> > Returns:> > str: A message indicating the promotion and new salary.> > '''> > self> .salary> +> => raise_amount> > return> f> '{self.name} has been promoted! New salary: ${self.salary:.2f}'> > def> retire(> self> ):> > '''> > Marks the employee as retired.> > Returns:> > str: A message indicating the retirement status.> > '''> > # Some implementation for retiring an employee> > return> f> '{self.name} has retired. Thank you for your service!'> # Access the Class docstring using help()> help> (Employee)> |
出力:
class Employee | A class representing an employee. | | Attributes: | name (str): The name of the employee. | age (int): The age of the employee. | department (str): The department the employee works in. | salary (float): The salary of the employee. | | Methods defined here: | | __init__(self, name, age, department, salary) | Initializes an Employee object. | | Parameters: | name (str): The name of the employee. | age (int): The age of the employee. | department (str): The department the employee works in. | salary (float): The salary of the employee. | | promote(self, raise_amount) | Promotes the employee and increases their salary. | | Parameters: | raise_amount (float): The raise amount to increase the salary. | | Returns: | str: A message indicating the promotion and new salary. | | retire(self) | Marks the employee as retired. | | Returns: | str: A message indicating the retirement status.
クラス内の docstring
クラスとメソッドの docstring を記述する方法を示す例を見てみましょう。 ヘルプ' docstring にアクセスするために使用されます。
Python3
class> ComplexNumber:> > '''> > This is a class for mathematical operations on complex numbers.> > Attributes:> > real (int): The real part of the complex number.> > imag (int): The imaginary part of the complex number.> > '''> > def> __init__(> self> , real, imag):> > '''> > The constructor for ComplexNumber class.> > Parameters:> > real (int): The real part of the complex number.> > imag (int): The imaginary part of the complex number.> > '''> > self> .real> => real> > self> .imag> => imag> > def> add(> self> , num):> > '''> > The function to add two Complex Numbers.> > Parameters:> > num (ComplexNumber): The complex number to be added.> > Returns:> > ComplexNumber: A complex number which contains the sum.> > '''> > re> => self> .real> +> num.real> > im> => self> .imag> +> num.imag> > return> ComplexNumber(re, im)> # Access the Class docstring using help()> help> (ComplexNumber)> # Access the method docstring using help()> help> (ComplexNumber.add)> |
出力:
Help on class ComplexNumber in module __main__: class ComplexNumber(builtins.objects) | This is a class for mathematical operations on complex numbers. | | Attributes: | real (int): The real part of complex number. | imag (int): The imaginary part of complex number. | | Methods defined here: | | __init__(self, real, imag) | The constructor for ComplexNumber class. | | Parameters: | real (int): The real part of complex number. | imag (int): The imaginary part of complex number. | | add(self, num) | The function to add two Complex Numbers. | | Parameters: | num (ComplexNumber): The complex number to be added. | | Returns: | ComplexNumber: A complex number which contains the sum. Help on method add in module __main__: add(self, num) unbound __main__.ComplexNumber method The function to add two Complex Numbers. Parameters: num (ComplexNumber): The complex number to be added. Returns: ComplexNumber: A complex number which contains the sum.
Python コメント、String、Docstring の違い
文字列: Python では、文字列は一重引用符 (‘ ) または二重引用符 ( ) で囲まれた一連の文字です。文字列はテキスト データを表すために使用され、文字、数字、記号、空白を含めることができます。これらは Python の基本的なデータ型の 1 つであり、さまざまな文字列メソッドを使用して操作できます。
皆さんは Python の docstring については理解しているはずですが、Python のコメントと docstring の違いについて疑問に思ったことはありますか?それらを見てみましょう。
これらは、読者にソース コードを理解させるために開発者が提供する有用な情報です。コード内で使用されているロジックまたはその一部について説明します。を使って書かれています
#>
シンボル。
例:
Python3
# Python program to demonstrate comments> print> (> 'GFG'> )> name> => 'Abhishek Shakya'> #demostrate String> |
出力:
GFG
一方、上記の Python Docstrings は、ドキュメントを Python モジュール、関数、クラス、メソッドに関連付ける便利な方法を提供します。