Când vine vorba de scrierea unui cod curat, bine documentat, dezvoltatorii Python au la dispoziție o armă secretă – documentele. Docstrings, prescurtare pentru șiruri de documentare, sunt vitale în transmiterea scopului și funcționalității Piton funcții, module și clase.
Care sunt docstring-urile în Python?
Piton șirurile de documentație (sau docstrings) oferă o modalitate convenabilă de a asocia documentația cu module Python , funcții, clase și metode. Este specificat în codul sursă care este folosit, ca un comentariu, pentru a documenta un anumit segment de cod. Spre deosebire de comentariile convenționale la codul sursă, documentul ar trebui să descrie ce face funcția, nu cum.
- Declararea Docstrings : Docstring-urile sunt declarate folosind „ghilimele simple triple” sau ghilimele duble triple chiar sub declarația clasei, metodei sau funcției. Toate funcțiile ar trebui să aibă un docstring.
- Accesarea Docstrings : Docstring-urile pot fi accesate folosind metoda __doc__ a obiectului sau folosind funcția de ajutor. Exemplele de mai jos demonstrează cum să declarați și să accesați un docstring.
Cum ar trebui să arate un docstring?
- Linia șirului de documente ar trebui să înceapă cu o literă majusculă și să se termine cu un punct.
- Prima linie ar trebui să fie o scurtă descriere.
- Dacă există mai multe rânduri în șirul de documentație, a doua linie trebuie să fie goală, separând vizual rezumatul de restul descrierii.
- Următoarele rânduri ar trebui să fie unul sau mai multe paragrafe care descriu convențiile de apelare ale obiectului, efectele secundare etc.
Docstrings în Python
Mai jos sunt subiectele pe care le vom trata în acest articol:
- Șiruri de caractere triple
- Google Style Docstrings
- Numpydoc Style Docstrings
- Docstrings cu o singură linie
- Docstrings cu mai multe linii
- Indentare în Docstrings
- Docstrings în clase
- Diferența dintre comentariile Python și documentele
Șiruri de caractere triple
Acesta este cel mai comun format docstring din Python. Aceasta implică utilizarea ghilimelelor triple (fie simple, fie duble) pentru a include textul documentației. Șirurile între ghilimele triple se pot întinde pe mai multe linii și sunt adesea plasate imediat sub definiția funcției, clasei sau modulului
Exemplul 1: Folosind ghilimele simple triple
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)> |
>
>
Ieșire:
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.>
Exemplul 2: Folosind ghilimele triple-duble
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)> |
>
>
Ieșire:
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
Documentele în stil Google urmează un format specific și sunt inspirate de ghidul de stil al documentației Google. Ele oferă o modalitate structurată de a documenta codul Python, inclusiv parametrii, valorile returnate și descrierile.
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> ))> |
generator de numere aleatoare java
>
>Ieșire
15>
Numpydoc Style Docstrings
Docstring-urile în stil Numpydoc sunt utilizate pe scară largă în comunitatea științifică și de analiză a datelor, în special pentru documentarea funcțiilor și claselor legate de calculele numerice și manipularea datelor. Este o extensie a documentelor în stil Google, cu câteva convenții suplimentare pentru documentarea parametrilor și a valorilor returnate.
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> ))> |
>
>Ieșire
0.5>
Docstrings cu o singură linie
După cum sugerează și numele, docstring-urile cu o singură linie se potrivesc într-o singură linie. Sunt folosite în cazuri evidente. Ofertele de închidere sunt pe aceeași linie cu ghilimelele de deschidere. Acest lucru arată mai bine pentru o linie. De exemplu:
Python3
def> power(a, b):> > ' '> 'Returns arg1 raised to power arg2.'> ' '> > > return> a> *> *> b> print> (power.__doc__)> |
>
>
Ieșire:
Returns arg1 raised to power arg2.>
Docstrings cu mai multe linii
Docstring-urile cu mai multe rânduri constau dintr-o linie de rezumat la fel ca un document de o linie, urmată de o linie goală, urmată de o descriere mai elaborată. Linia de rezumat poate fi pe aceeași linie cu ghilimelele de deschidere sau pe linia următoare. Exemplul de mai jos arată un șir documentar cu mai multe linii.
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> ))> |
>
>
Ieșire:
8>
Indentare în Docstrings
Întregul șir documentar este indentat la fel ca ghilimelele din prima linie. Instrumentele de procesare Docstring vor îndepărta o cantitate uniformă de indentare din a doua și din rândurile următoare ale docstring, egală cu indentația minimă a tuturor liniilor care nu sunt goale după prima linie. Orice indentare din prima linie a documentului (adică până la prima linie nouă) este nesemnificativă și eliminată. Indentarea relativă a liniilor ulterioare din docstring este păstrată.
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)> |
>
>
Ieșire:
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 în clase
Să luăm un exemplu pentru a arăta cum să scriem documente pentru o clasă și metoda „ Ajutor' este folosit pentru a accesa documentul.
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)> |
>
>
Ieșire:
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.>
Diferența dintre comentariile Python, String și Docstrings
Șir: în Python, un șir este o secvență de caractere închisă între ghilimele simple (‘ ‘) sau ghilimele duble ( ). Șirurile sunt folosite pentru a reprezenta datele text și pot conține litere, cifre, simboluri și spații albe. Ele sunt unul dintre tipurile de date fundamentale din Python și pot fi manipulate folosind diverse metode de șir.
Cu toții trebuie să aveți o idee despre docstrings Python, dar v-ați întrebat vreodată care este diferența dintre comentariile Python și docstrings? Să aruncăm o privire la ele.
Sunt informații utile pe care dezvoltatorii le oferă pentru a face cititorul să înțeleagă codul sursă. Acesta explică logica sau o parte din ea folosită în cod. Este scris folosind
#>
simboluri.
Exemplu:
Python3
stlc
# Python program to demonstrate comments> print> (> 'GFG'> )> name> => 'Abhishek Shakya'> #demostrate String> |
>
>
Ieșire:
GFG>
În timp ce Python Docstrings, așa cum s-a menționat mai sus, oferă o modalitate convenabilă de a asocia documentația cu modulele, funcțiile, clasele și metodele Python.