Kad runa ir par tīra, labi dokumentēta koda rakstīšanu, Python izstrādātāju rīcībā ir slepens ierocis – dokumentu virknes. Dokumentu virknes, kas ir saīsinājums no dokumentācijas virknēm, ir ļoti svarīgas, lai atspoguļotu programmas mērķi un funkcionalitāti. Python funkcijas, moduļi un klases.
Kādas ir Python dokumentu virknes?
Python dokumentācijas virknes (vai dokumentācijas virknes) nodrošina ērtu veidu, kā saistīt dokumentāciju ar Python moduļi , funkcijas, klases un metodes. Tas ir norādīts avota kodā, kas tiek izmantots, piemēram, komentārs, lai dokumentētu noteiktu koda segmentu. Atšķirībā no parastajiem pirmkoda komentāriem, dokumentācijas virknei jāapraksta, ko funkcija dara, nevis kā.
- Docstring deklarēšana : Dokumentu virknes tiek deklarētas, izmantojot trīskāršās pēdiņas vai trīskāršās dubultpēdiņas tieši zem klases, metodes vai funkcijas deklarācijas. Visām funkcijām ir jābūt dokumentu virknei.
- Piekļuve dokumentu virknēm : Dokumentu virknēm var piekļūt, izmantojot objekta __doc__ metodi vai palīdzības funkciju. Tālāk minētie piemēri parāda, kā deklarēt dokumentu virkni un tai piekļūt.
Kādai vajadzētu izskatīties dokstringam?
- Dokumenta virknes rindai jāsākas ar lielo burtu un jābeidzas ar punktu.
- Pirmajā rindā jābūt īsam aprakstam.
- Ja dokumentācijas virknē ir vairāk rindu, otrajai rindai jābūt tukšai, vizuāli atdalot kopsavilkumu no pārējā apraksta.
- Nākamajās rindās ir jābūt vienai vai vairākām rindkopām, kas apraksta objekta izsaukšanas metodes, blakusparādības utt.
Docstrings programmā Python
Tālāk ir norādītas tēmas, kuras mēs apskatīsim šajā rakstā:
- Trīspēdu stīgas
- Google stila dokumentu virknes
- Numpydoc stila dokumentu virknes
- Vienas rindas dokumentu virknes
- Vairāku rindu dokumentu virknes
- Atkāpe Docstrings
- Docstrings klasēs
- Atšķirība starp Python komentāriem un dokumentu virknēm
Trīspēdu stīgas
Šis ir visizplatītākais Python dokumentu virkņu formāts. Tas ietver trīspēdiņu (vienkāršā vai dubultā) izmantošanu, lai pievienotu dokumentācijas tekstu. Trīspēdiņu virknes var aptvert vairākas rindas un bieži tiek novietotas tieši zem funkcijas, klases vai moduļa definīcijas.
1. piemērs: Trīskāršu pēdiņu izmantošana
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)> |
>
>
Izvade:
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. piemērs: Izmantojot trīskāršās-dubultās pēdiņas
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)> |
>
>
Izvade:
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 stila dokumentu virknes
Google stila dokumentu virknes atbilst noteiktam formātam, un tās ir iedvesmotas no Google dokumentācijas stila rokasgrāmatas. Tie nodrošina strukturētu veidu, kā dokumentēt Python kodu, tostarp parametrus, atgriešanas vērtības un aprakstus.
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> ))> |
>
>Izvade
15>
Numpydoc stila dokumentu virknes
Numpydoc stila dokumentācijas virknes tiek plaši izmantotas zinātnes un datu analīzes aprindās, jo īpaši, lai dokumentētu funkcijas un klases, kas saistītas ar skaitliskiem aprēķiniem un datu manipulācijām. Tas ir Google stila dokumentu virkņu paplašinājums ar dažām papildu konvencijām parametru un atgriešanas vērtību dokumentēšanai.
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> ))> |
>
>Izvade
0.5>
Vienas rindas dokumentu virknes
Kā norāda nosaukums, vienas rindas dokumentu virknes ietilpst vienā rindā. Tos izmanto acīmredzamos gadījumos. Noslēguma pēdiņas atrodas tajā pašā rindā kā sākuma pēdiņas. Tas izskatās labāk vienkāršajiem. Piemēram:
Python3
def> power(a, b):> > ' '> 'Returns arg1 raised to power arg2.'> ' '> > > return> a> *> *> b> print> (power.__doc__)> |
>
>
Izvade:
Returns arg1 raised to power arg2.>
Vairāku rindu dokumentu virknes
Vairāku rindu dokumentu virknes sastāv no kopsavilkuma rindiņas tāpat kā vienas rindiņas dokumentu virknes, kam seko tukša rindiņa, kam seko detalizētāks apraksts. Kopsavilkuma rindiņa var būt tajā pašā rindiņā ar sākuma pēdiņām vai nākamajā rindā. Tālāk esošajā piemērā ir parādīta vairāku rindu dokumentu virkne.
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> ))> |
>
>
Izvade:
8>
Atkāpe Docstrings
Visa dokumenta virkne ir ievilkta tāpat kā pēdiņas tās pirmajā rindā. Dokumentu virknes apstrādes rīki noņems vienādu atkāpi no otrās un turpmākajām dokumentu virknes rindiņām, kas ir vienāda ar minimālo atkāpi visās rindās, kas nav tukšas pēc pirmās rindas. Jebkura atkāpe dokumenta virknes pirmajā rindā (t.i., līdz pirmajai jaunajai rindai) ir nenozīmīga un tiek noņemta. Dokumentu virknes vēlāko rindu relatīvā atkāpe tiek saglabāta.
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)> |
>
>
Izvade:
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.>
Docstrings klasēs
Ņemsim piemēru, lai parādītu, kā rakstīt dokumentu virknes klasei un metodei ' palīdzēt' tiek izmantots, lai piekļūtu dokumentācijas virknei.
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)> |
>
>
Izvade:
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.>
Atšķirība starp Python komentāriem, virknēm un dokumentu virknēm
Virkne: programmā Python virkne ir rakstzīmju secība, kas ietverta vienpēdiņās (‘’) vai dubultpēdiņās ( ). Virknes tiek izmantotas teksta datu attēlošanai, un tās var saturēt burtus, ciparus, simbolus un atstarpes. Tie ir viens no Python pamatdatu tipiem, un ar tiem var manipulēt, izmantojot dažādas virkņu metodes.
Jums visiem noteikti ir priekšstats par Python dokumentu virknēm, taču vai esat kādreiz domājuši, kāda ir atšķirība starp Python komentāriem un dokumentu virknēm? Apskatīsim tos.
Tā ir noderīga informācija, ko izstrādātāji sniedz, lai lasītājs saprastu avota kodu. Tas izskaidro kodā izmantoto loģiku vai tās daļu. Tas ir uzrakstīts, izmantojot
#>
simboliem.
Piemērs:
Python3
# Python program to demonstrate comments> print> (> 'GFG'> )> name> => 'Abhishek Shakya'> #demostrate String> |
>
>
Izvade:
GFG>
Tā kā Python Docstrings, kā minēts iepriekš, nodrošina ērtu veidu, kā saistīt dokumentāciju ar Python moduļiem, funkcijām, klasēm un metodēm.
koku un grafu teorija