Quando si tratta di scrivere codice pulito e ben documentato, gli sviluppatori Python hanno un'arma segreta a loro disposizione: le docstring. Le docstring, abbreviazione di stringhe di documentazione, sono fondamentali per trasmettere lo scopo e la funzionalità di Pitone funzioni, moduli e classi.
Quali sono le docstring in Python?
Pitone le stringhe di documentazione (o docstrings) forniscono un modo conveniente per associare la documentazione Moduli Python , funzioni, classi e metodi. È specificato nel codice sorgente che viene utilizzato, come un commento, per documentare uno specifico segmento di codice. A differenza dei commenti convenzionali del codice sorgente, la docstring dovrebbe descrivere cosa fa la funzione, non come.
- Dichiarazione di Docstring : Le docstring vengono dichiarate utilizzando 'triple virgolette singole' o triple virgolette doppie appena sotto la dichiarazione di classe, metodo o funzione. Tutte le funzioni dovrebbero avere una docstring.
- Accesso a Docstring : È possibile accedere alle docstring utilizzando il metodo __doc__ dell'oggetto o utilizzando la funzione di aiuto. Gli esempi seguenti dimostrano come dichiarare e accedere a una docstring.
Come dovrebbe essere una docstring?
- La riga della stringa del documento deve iniziare con una lettera maiuscola e terminare con un punto.
- La prima riga dovrebbe essere una breve descrizione.
- Se nella stringa della documentazione sono presenti più righe, la seconda riga dovrebbe essere vuota, separando visivamente il riepilogo dal resto della descrizione.
- Le righe seguenti dovrebbero essere uno o più paragrafi che descrivono le convenzioni di chiamata dell'oggetto, gli effetti collaterali, ecc.
Docstring in Python
Di seguito sono riportati gli argomenti che tratteremo in questo articolo:
- Stringhe con virgolette triple
- Documenti in stile Google
- Docstring in stile Numpydoc
- Docstring di una riga
- Docstring multilinea
- Rientro in Docstrings
- Docstring nelle classi
- Differenza tra commenti Python e docstring
Stringhe con virgolette triple
Questo è il formato docstring più comune in Python. Implica l'uso di virgolette triple (singole o doppie) per racchiudere il testo della documentazione. Le stringhe tra virgolette triple possono estendersi su più righe e spesso vengono posizionate immediatamente sotto la definizione di funzione, classe o modulo
Esempio 1: Utilizzo di virgolette singole 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)> |
>
>
Produzione:
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.>
Esempio 2: Utilizzo di virgolette doppie
Python3
L'attrice Rubina Dilaik
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)> |
>
>
Produzione:
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.>
Documenti in stile Google
Le docstring in stile Google seguono un formato specifico e si ispirano alla guida allo stile della documentazione di Google. Forniscono un modo strutturato per documentare il codice Python, inclusi parametri, valori restituiti e descrizioni.
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>))> |
>
>Produzione
15>
Docstring in stile Numpydoc
Le docstring in stile Numpydoc sono ampiamente utilizzate nella comunità scientifica e di analisi dei dati, in particolare per documentare funzioni e classi relative ai calcoli numerici e alla manipolazione dei dati. È un'estensione delle docstring in stile Google, con alcune convenzioni aggiuntive per documentare parametri e valori restituiti.
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>))> |
rimuovendo l'ultimo commit git
>
>Produzione
0.5>
Docstring di una riga
Come suggerisce il nome, le docstring di una riga stanno in una riga. Sono usati nei casi ovvi. Le virgolette di chiusura sono sulla stessa riga delle virgolette di apertura. Questo sembra migliore per le battute di una battuta. Per esempio:
Python3
def> power(a, b):> >' '> 'Returns arg1 raised to power arg2.'> ' '> > >return> a>*>*>b> print>(power.__doc__)> |
>
>
Produzione:
Returns arg1 raised to power arg2.>
Docstring multilinea
Le docstring su più righe sono costituite da una riga di riepilogo proprio come una docstring di una riga, seguita da una riga vuota, seguita da una descrizione più elaborata. La riga di riepilogo può trovarsi sulla stessa riga delle virgolette di apertura o sulla riga successiva. L'esempio seguente mostra una docstring su più righe.
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>))> |
>
>
Produzione:
8>
Rientro in Docstrings
L'intera docstring ha lo stesso rientro delle virgolette nella prima riga. Gli strumenti di elaborazione della docstring rimuoveranno una quantità uniforme di rientro dalla seconda e dalle successive righe della docstring, pari al rientro minimo di tutte le righe non vuote dopo la prima riga. Qualsiasi rientro nella prima riga della docstring (cioè fino alla prima nuova riga) è insignificante e viene rimosso. Il rientro relativo delle righe successive nella docstring viene mantenuto.
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)> |
>
>
Produzione:
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 nelle classi
Facciamo un esempio per mostrare come scrivere docstring per una classe e il metodo ' aiuto' viene utilizzato per accedere alla 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)> |
>
>
Produzione:
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.>
Differenza tra commenti Python, String e Docstrings
Stringa: In Python, una stringa è una sequenza di caratteri racchiusa tra virgolette singole (' ) o virgolette doppie ( ). Le stringhe vengono utilizzate per rappresentare dati di testo e possono contenere lettere, numeri, simboli e spazi bianchi. Sono uno dei tipi di dati fondamentali in Python e possono essere manipolati utilizzando vari metodi di stringa.
Dovete tutti avere un'idea delle docstring Python, ma vi siete mai chiesti qual è la differenza tra commenti Python e docstring? Diamo un'occhiata a loro.
comando arp-a
Sono informazioni utili che gli sviluppatori forniscono per far comprendere al lettore il codice sorgente. Spiega la logica o parte di essa utilizzata nel codice. È scritto usando
#>
simboli.
Esempio:
Python3
# Python program to demonstrate comments> print>(>'GFG'>)> name>=> 'Abhishek Shakya'> #demostrate String> |
>
>
Produzione:
GFG>
Mentre Python Docstrings, come menzionato sopra, fornisce un modo conveniente per associare la documentazione a moduli, funzioni, classi e metodi Python.