Dokumentacja Pythona
Jeśli chodzi o pisanie czystego, dobrze udokumentowanego kodu, programiści Pythona mają do dyspozycji tajną broń – dokumenty. Dokumenty, skrót od ciągów dokumentacji, są niezbędne do przekazania celu i funkcjonalności Pyton funkcje, moduły i klasy.
Jakie są dokumenty w Pythonie?
Pyton Ciągi dokumentacji (lub dokumenty) zapewniają wygodny sposób powiązania dokumentacji z Moduły Pythona , funkcje, klasy i metody. Jest to określone w kodzie źródłowym, który służy, podobnie jak komentarz, do dokumentowania określonego segmentu kodu. W przeciwieństwie do konwencjonalnych komentarzy do kodu źródłowego, dokumentacja powinna opisywać, co funkcja robi, a nie jak.
- Deklarowanie dokumentów : Dokumenty są deklarowane przy użyciu „potrójnych cudzysłowów” lub potrójnych cudzysłowów tuż pod deklaracją klasy, metody lub funkcji. Wszystkie funkcje powinny mieć dokumentację.
- Dostęp do dokumentów : Dostęp do dokumentów można uzyskać za pomocą metody __doc__ obiektu lub funkcji pomocy. Poniższe przykłady pokazują, jak zadeklarować ciąg dokumentów i uzyskać do niego dostęp.
Jak powinien wyglądać dokument?
- Wiersz ciągu dokumentu powinien zaczynać się od dużej litery i kończyć kropką.
- Pierwsza linia powinna zawierać krótki opis.
- Jeżeli w ciągu dokumentacji jest więcej wierszy, drugi wiersz powinien być pusty, wizualnie oddzielając podsumowanie od reszty opisu.
- Kolejne wiersze powinny zawierać jeden lub więcej akapitów opisujących konwencje wywoływania obiektu, skutki uboczne itp.
Dokumenty w Pythonie
Poniżej znajdują się tematy, które omówimy w tym artykule:
- Ciągi znaków w potrójnym cudzysłowie
- Dokumenty dotyczące stylu Google
- Dokumentacja w stylu Numpydoc
- Dokumenty jednowierszowe
- Dokumenty wielowierszowe
- Wcięcia w dokumentach
- Dokumenty na zajęciach
- Różnica między komentarzami w Pythonie a dokumentami
Ciągi znaków w potrójnym cudzysłowie
Jest to najpopularniejszy format ciągu dokumentów w Pythonie. Polega na użyciu potrójnych cudzysłowów (pojedynczych lub podwójnych) w celu umieszczenia tekstu dokumentacji. Ciągi znaków w potrójnych cudzysłowach mogą obejmować wiele wierszy i często są umieszczane bezpośrednio pod definicją funkcji, klasy lub modułu
Przykład 1: Używanie potrójnych cudzysłowów
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)> |
Wyjście:
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.
Przykład 2: Używanie potrójnych cudzysłowów
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)> |
Wyjście:
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.
Dokumenty dotyczące stylu Google
Dokumentacja w stylu Google ma określony format i jest inspirowana przewodnikiem po stylu dokumentacji Google. Zapewniają uporządkowany sposób dokumentowania kodu Pythona, w tym parametrów, wartości zwracanych i opisów.
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> ))> |
Wyjście
15
Dokumentacja w stylu Numpydoc
Dokumenty w stylu Numpydoc są szeroko stosowane w społeczności naukowej i zajmującej się analizą danych, szczególnie do dokumentowania funkcji i klas związanych z obliczeniami numerycznymi i manipulacją danymi. Jest to rozszerzenie dokumentów w stylu Google, z kilkoma dodatkowymi konwencjami dokumentowania parametrów i zwracanych wartości.
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> ))> |
Wyjście
0.5
Dokumenty jednowierszowe
Jak sama nazwa wskazuje, jednowierszowe dokumenty mieszczą się w jednej linii. Stosuje się je w oczywistych przypadkach. Cytaty zamykające znajdują się w tej samej linii, co cytaty otwierające. Wygląda to lepiej w przypadku jednowierszowych. Na przykład:
Python3
def> power(a, b):> > ' '> 'Returns arg1 raised to power arg2.'> ' '> > > return> a> *> *> b> print> (power.__doc__)> |
Wyjście:
Returns arg1 raised to power arg2.
Dokumenty wielowierszowe
Dokumenty wieloliniowe składają się z linii podsumowania, podobnie jak ciągi dokumentów jednowierszowych, po której następuje pusta linia, po której następuje bardziej szczegółowy opis. Wiersz podsumowania może znajdować się w tym samym wierszu co cytaty otwierające lub w wierszu następnym. Poniższy przykład przedstawia wieloliniowy dokument.
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> ))> |
Wyjście:
8
Wcięcia w dokumentach
Cały dokument ma wcięcie takie samo, jak cudzysłowy w pierwszym wierszu. Narzędzia do przetwarzania dokumentów usuwają jednakową wielkość wcięcia z drugiej i kolejnych linii dokumentu, równą minimalnemu wcięciu wszystkich niepustych linii po pierwszej linii. Wszelkie wcięcia w pierwszym wierszu dokumentu (tj. do pierwszego nowego wiersza) są nieistotne i usuwane. Względne wcięcie późniejszych wierszy dokumentu zostaje zachowane.
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)> |
Wyjście:
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.
Dokumenty na zajęciach
Weźmy przykład, aby pokazać, jak pisać dokumenty dla klasy i metody „ pomoc' służy do uzyskiwania dostępu do dokumentu.
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)> |
Wyjście:
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.
Różnica między komentarzami w Pythonie, ciągami znaków i dokumentami
Ciąg: W Pythonie ciąg znaków to sekwencja znaków ujęta w pojedynczy cudzysłów („”) lub podwójny cudzysłów ( ). Ciągi służą do reprezentowania danych tekstowych i mogą zawierać litery, cyfry, symbole i białe znaki. Są jednym z podstawowych typów danych w Pythonie i można nimi manipulować za pomocą różnych metod łańcuchowych.
Wszyscy na pewno macie pojęcie o ciągach dokumentów w Pythonie, ale czy kiedykolwiek zastanawialiście się, jaka jest różnica między komentarzami w Pythonie a dokumentami? Przyjrzyjmy się im.
Są to przydatne informacje dostarczane przez programistów, aby czytelnik mógł zrozumieć kod źródłowy. Wyjaśnia logikę lub jej część zastosowaną w kodzie. Jest napisane za pomocą
#>
symbolika.
Przykład:
Python3
# Python program to demonstrate comments> print> (> 'GFG'> )> name> => 'Abhishek Shakya'> #demostrate String> |
Wyjście:
GFG
Natomiast Python Docstrings, jak wspomniano powyżej, zapewnia wygodny sposób powiązania dokumentacji z modułami, funkcjami, klasami i metodami Pythona.