Ko gre za pisanje čiste, dobro dokumentirane kode, imajo razvijalci Pythona na voljo skrivno orožje – nize dokumentov. Dokumentacijski nizi, okrajšava za dokumentacijske nize, so ključnega pomena za prenos namena in funkcionalnosti Python funkcije, moduli in razredi.
Kaj so dokumentni nizi v Pythonu?
Python nizi dokumentacije (ali nizi dokumentov) zagotavljajo priročen način povezovanja dokumentacije z Moduli Python , funkcije, razredi in metode. Določen je v izvorni kodi, ki se tako kot komentar uporablja za dokumentiranje določenega segmenta kode. Za razliko od običajnih komentarjev izvorne kode mora dokumentni niz opisovati, kaj funkcija počne, ne kako.
- Deklariranje nizov dokumentov : Dokumentni nizi so deklarirani s pomočjo 'trojnih enojnih narekovajev' ali trojnih dvojnih narekovajev tik pod deklaracijo razreda, metode ali funkcije. Vse funkcije morajo imeti dokumentni niz.
- Dostop do Docstrings : Do nizov dokumentov lahko dostopate z metodo __doc__ objekta ali s funkcijo pomoči. Spodnji primeri prikazujejo, kako deklarirati in dostopati do niza dokumentov.
Kako naj izgleda niz dokumentov?
- Vrstica niza dokumenta se mora začeti z veliko začetnico in končati s piko.
- Prva vrstica naj bo kratek opis.
- Če je v dokumentacijskem nizu več vrstic, mora biti druga vrstica prazna in vizualno ločiti povzetek od preostalega opisa.
- Naslednje vrstice naj bodo en ali več odstavkov, ki opisujejo klicne konvencije objekta, stranske učinke itd.
Dokumentni nizi v Pythonu
Spodaj so teme, ki jih bomo obravnavali v tem članku:
- Nizi s trojnimi narekovaji
- Google Style Docstrings
- Numpydoc Style Docstrings
- Enovrstični dokumentni nizi
- Večvrstični dokumentni nizi
- Zamik v nizih dokumentov
- Nizi dokumentov v razredih
- Razlika med komentarji Python in nizi dokumentov
Nizi s trojnimi narekovaji
To je najpogostejši format niza dokumentov v Pythonu. Vključuje uporabo trojnih narekovajev (enojnih ali dvojnih) za pritrditev besedila dokumentacije. Nizi s trojnimi narekovaji lahko zajemajo več vrstic in so pogosto postavljeni takoj pod definicijo funkcije, razreda ali modula
Primer 1: Uporaba trojnih enojnih narekovajev
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)> |
>
>
Izhod:
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.>
Primer 2: Uporaba triple-double narekovajev
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)> |
>
>
Izhod:
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
Dokumentacijski nizi v Googlovem slogu sledijo določeni obliki in se zgledujejo po Googlovem vodniku po slogu dokumentacije. Zagotavljajo strukturiran način za dokumentiranje kode Python, vključno s parametri, vrnjenimi vrednostmi in opisi.
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> ))> |
>
>Izhod
15>
Numpydoc Style Docstrings
Dokumentarni nizi v slogu Numpydoc se pogosto uporabljajo v znanstveni skupnosti in skupnosti za analizo podatkov, zlasti za dokumentiranje funkcij in razredov, povezanih z numeričnimi izračuni in manipulacijo podatkov. Je razširitev nizov dokumentov v Googlovem slogu z nekaterimi dodatnimi konvencijami za dokumentiranje parametrov in vrnjenih vrednosti.
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> ))> |
>
>Izhod
0.5>
Enovrstični dokumentni nizi
Kot že ime pove, se enovrstični nizi dokumentov prilegajo eni vrstici. Uporabljajo se v očitnih primerih. Zaključni narekovaji so v isti vrstici kot začetni narekovaji. To izgleda bolje za enovrstične. Na primer:
Python3
def> power(a, b):> > ' '> 'Returns arg1 raised to power arg2.'> ' '> > > return> a> *> *> b> print> (power.__doc__)> |
>
>
Izhod:
Returns arg1 raised to power arg2.>
Večvrstični dokumentni nizi
Večvrstični dokumentni nizi so sestavljeni iz vrstice s povzetkom, tako kot enovrstični dokumentni niz, ki ji sledi prazna vrstica, ki ji sledi podrobnejši opis. Vrstica povzetka je lahko v isti vrstici kot začetni narekovaji ali v naslednji vrstici. Spodnji primer prikazuje večvrstični dokumentni niz.
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> ))> |
>
>
Izhod:
8>
Zamik v nizih dokumentov
Celoten niz dokumenta je zamaknjen enako kot narekovaji v prvi vrstici. Orodja za obdelavo niza dokumentov bodo odstranila enakomerno količino zamika iz druge in nadaljnjih vrstic niza dokumenta, ki je enak najmanjšemu zamiku vseh nepraznih vrstic za prvo vrstico. Vsak zamik v prvi vrstici niza dokumenta (tj. do prve nove vrstice) je nepomemben in odstranjen. Relativni zamik kasnejših vrstic v dokumentnem nizu se ohrani.
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)> |
>
>
Izhod:
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.>
Dokumentarni nizi v razredih
Vzemimo primer, da pokažemo, kako napisati nize dokumentov za razred in metodo ' pomoč' se uporablja za dostop do niza dokumentov.
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)> |
>
>
Izhod:
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.>
Razlika med komentarji Python, String in Docstrings
Niz: V Pythonu je niz zaporedje znakov v enojnih narekovajih (‘ ‘) ali dvojnih narekovajih ( ). Nizi se uporabljajo za predstavitev besedilnih podatkov in lahko vsebujejo črke, številke, simbole in presledke. So eden temeljnih tipov podatkov v Pythonu in z njimi je mogoče manipulirati z različnimi metodami nizov.
Verjetno imate vsi predstavo o dokumentnih nizih Python, vendar ste se kdaj vprašali, kakšna je razlika med komentarji Python in dokumentnimi nizi? Oglejmo si jih.
So koristne informacije, ki jih razvijalci zagotovijo, da bralec razume izvorno kodo. Pojasnjuje logiko ali njen del, uporabljen v kodi. Napisana je z uporabo
#>
simboli.
primer:
Python3
# Python program to demonstrate comments> print> (> 'GFG'> )> name> => 'Abhishek Shakya'> #demostrate String> |
zamenjaj vso javo
>
>
Izhod:
GFG>
Medtem ko Python Docstrings, kot je omenjeno zgoraj, zagotavlja priročen način povezovanja dokumentacije z moduli, funkcijami, razredi in metodami Python.