Рядки документів Python

Коли справа доходить до написання чистого, добре задокументованого коду, розробники Python мають у своєму розпорядженні секретну зброю – рядки документації. Рядки документації, скорочення від рядків документації, життєво важливі для передачі мети та функціональності Python функції, модулі та класи.

Що таке рядки документів у Python?

Python рядки документації (або рядки документації) забезпечують зручний спосіб асоціювання документації з Модулі Python , функції, класи та методи. Це вказано у вихідному коді, який використовується, як коментар, для документування певного сегмента коду. На відміну від звичайних коментарів до вихідного коду, рядок документації має описувати, що функція робить, а не як.

  • Оголошення Docstrings : Рядки документації оголошуються за допомогою «потрійних одинарних лапок» або потрійних подвійних лапок безпосередньо під оголошенням класу, методу або функції. Усі функції повинні мати рядок документації.
  • Доступ до Docstrings : Доступ до рядків документів можна отримати за допомогою методу __doc__ об’єкта або за допомогою функції довідки. Наведені нижче приклади демонструють, як оголосити рядок документації та отримати доступ до неї.

Як має виглядати рядок документації?

  • Рядок документа повинен починатися з великої літери і закінчуватися крапкою.
  • Перший рядок має бути коротким описом.
  • Якщо в рядку документації є більше рядків, другий рядок має бути порожнім, візуально відокремлюючи резюме від решти опису.
  • Наступні рядки мають бути одним або декількома абзацами з описом умов виклику об’єкта, побічних ефектів тощо.

Документаційні рядки в Python

Нижче наведено теми, які ми розглянемо в цій статті:

  • Рядки в потрійних лапках
  • Google Style Docstrings
  • Рядки документів у стилі Numpydoc
  • Однорядкові рядки документів
  • Багаторядкові рядки документів
  • Відступи в Docstrings
  • Рядки документів у класах
  • Різниця між коментарями Python і рядками документації

Рядки в потрійних лапках

Це найпоширеніший формат рядка документів у Python. Він передбачає використання потрійних лапок (одинарних або подвійних) для укладення тексту документації. Рядки в потрійних лапках можуть займати кілька рядків і часто розміщуються безпосередньо під визначенням функції, класу або модуля

приклад 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 Style Docstrings

Документаційні рядки в стилі 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 широко використовуються в науковому співтоваристві та спільноті аналізу даних, зокрема для документування функцій і класів, пов’язаних із чисельними обчисленнями та маніпулюванням даними. Це розширення рядків документів у стилі Google з деякими додатковими угодами для документування параметрів і значень, що повертаються.

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 

Однорядкові рядки документів

Як випливає з назви, однорядкові рядки документів поміщаються в один рядок. Вони використовуються в очевидних випадках. Закриваючі лапки знаходяться в одному рядку з початковими. Це виглядає краще для однорядкових. Наприклад:

Python3




def> power(a, b):> > ' '> 'Returns arg1 raised to power arg2.'> ' '> > > return> a> *> *> b> print> (power.__doc__)>

Вихід:

Returns arg1 raised to power arg2. 

Багаторядкові рядки документів

Багаторядкові рядки документації складаються з підсумкового рядка, як і однорядковий рядок документації, за яким іде порожній рядок, після якого йде детальніший опис. Підсумковий рядок може бути в одному рядку з початковими лапками або в наступному рядку. У прикладі нижче показано багаторядковий рядок документації.

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 

Відступи в Docstrings

Весь рядок документа має такий самий відступ, як і лапки в його першому рядку. Інструменти обробки рядка документації знімуть рівномірний відступ із другого та подальших рядків рядка документації, що дорівнює мінімальному відступу всіх непорожніх рядків після першого рядка. Будь-який відступ у першому рядку рядка документації (тобто до першого нового рядка) є незначним і видаляється. Відносний відступ наступних рядків у рядку документації зберігається.

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. 

Рядки документів у класах

Розглянемо приклад, щоб показати, як написати рядки документації для класу та методу ‘ допомогти' використовується для доступу до рядка документації.

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 і Docstrings

Рядок: у Python рядок — це послідовність символів, укладених в одинарні лапки (‘ ‘) або подвійні лапки ( ). Рядки використовуються для представлення текстових даних і можуть містити літери, цифри, символи та пробіли. Вони є одним із основних типів даних у Python, і ними можна маніпулювати за допомогою різних методів рядків.

Ви, напевно, маєте уявлення про рядки документів Python, але чи замислювалися ви коли-небудь про різницю між коментарями Python і рядками документів? Давайте подивимося на них.

Це корисна інформація, яку розробники надають, щоб читач міг зрозуміти вихідний код. Він пояснює логіку або її частину, яка використовується в коді. Він написаний за допомогою

#>

символи.

приклад:

Python3




# Python program to demonstrate comments> print> (> 'GFG'> )> name> => 'Abhishek Shakya'> #demostrate String>

Вихід:

GFG 

У той час як Python Docstrings, як згадувалося вище, забезпечує зручний спосіб зв’язування документації з модулями, функціями, класами та методами Python.