Python Docstrings (med eksempler)

I denne opplæringen vil vi lære om Python docstrings. Mer spesifikt vil vi lære hvordan og hvorfor dokstrings brukes ved hjelp av eksempler.

Python docstrings er strengbokstavene som vises rett etter definisjonen av en funksjon, metode, klasse eller modul. La oss ta et eksempel.

Eksempel 1: Docstrings

 def square(n): '''Takes in a number n, returns the square of n''' return n**2

Her er strengen bokstavelig:

 '' Tar inn et tall n, returnerer kvadratet til n '' '

Inne trippel anførselstegn er docstring av funksjonen square()som det ser ut rett etter sin definisjon.

Merk: Vi kan også bruke trippel """sitater for å lage dokstringer.

Python-kommentarer vs Docstrings

Python-kommentarer

Kommentarer er beskrivelser som hjelper programmerere å bedre forstå intensjonen og funksjonaliteten til programmet. De blir fullstendig ignorert av Python-tolk.

I Python bruker vi hash-symbolet for #å skrive en kommentar med en linje. For eksempel,

 # Program to print "Hello World" print("Hello World") 

Python-kommentarer ved hjelp av strenger

Hvis vi ikke tilordner strenger til noen variabel, fungerer de som kommentarer. For eksempel,

 "I am a single-line comment" ''' I am a multi-line comment! ''' print("Hello World")

Merk: Vi bruker trippel anførselstegn for streng med flere linjer.

Python docstrings

Som nevnt ovenfor er Python docstrings strenger som brukes rett etter definisjonen av en funksjon, metode, klasse eller modul (som i eksempel 1 ). De brukes til å dokumentere koden vår.

Vi har tilgang til disse dokumentene ved hjelp av __doc__attributtet.

Python __doc__-attributt

Når strenglitteraturer er tilstede like etter definisjonen av en funksjon, modul, klasse eller metode, er de assosiert med objektet som __doc__attributt. Vi kan senere bruke denne attributtet for å hente denne dokstringen.

Eksempel 2: Utskrift av dokstring

 def square(n): '''Takes in a number n, returns the square of n''' return n**2 print(square.__doc__)

Produksjon

 Tar inn et tall n, returnerer kvadratet til n

Her square()kan du få tilgang til dokumentasjonen for funksjonen vår ved hjelp av __doc__attributtet.

La oss nå se på dokstrings for den innebygde funksjonen print():

Eksempel 3: Dokstrenger for den innebygde utskriftsfunksjonen ()

 print(print.__doc__)

Produksjon

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Skriver ut verdiene til en strøm eller til sys.stdout som standard. Valgfrie søkeordargumenter: fil: et fillignende objekt (strøm); er standard til gjeldende sys.stdout. sep: streng satt inn mellom verdiene, standard et mellomrom. slutt: streng lagt til etter den siste verdien, standard en ny linje. flush: om du skal tømme strømmen med makt.

Her kan vi se at dokumentasjonen til print()funksjonen er tilstede som __doc__attributt for denne funksjonen.

Enkelts doktrings i Python

Enkel linje dokstringer er dokumentene som passer i en linje.

Standardkonvensjoner for å skrive doktringer med en linje:

  • Selv om de er enkeltlinjede, bruker vi fortsatt de trippel anførselstegn rundt disse dokstringene, ettersom de lett kan utvides senere.
  • Avslutningskursene er på samme linje som åpningskursene.
  • Det er ingen tom linje hverken før eller etter doktringen.
  • De skal ikke være beskrivende, men de må følge "Gjør dette, returner den" -strukturen som slutter med en periode.

La oss ta et eksempel.

Eksempel 4: Skriv dokumentlinjer med en linje for en funksjon

 def multiplier(a, b): """Takes in two numbers, returns their product.""" return a*b

Multi-line Docstrings i Python

Flerstrengede dokstringer består av en oppsummeringslinje akkurat som en linjedokstring, etterfulgt av en tom linje, etterfulgt av en mer utførlig beskrivelse.

PEP 257-dokumentet gir standardkonvensjoner for å skrive doktrings med flere linjer for forskjellige objekter.

Noen er listet opp nedenfor:

1. Dokstrings for Python-moduler

  • Dokstringene for Python-moduler bør liste opp alle tilgjengelige klasser, funksjoner, objekter og unntak som importeres når modulen importeres.
  • They should also have a one-line summary for each item.

They are written at the beginning of the Python file.

Let's look at the docstrings for the builtin module in Python called pickle.

Example 4: Docstrings of Python module

 import pickle print(pickle.__doc__)

Output

 Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formats

Here, we can see that the docstring written at the beginning of the pickle.py module file can be accessed as its docstring.

2. Docstrings for Python Functions

  • The docstring for a function or method should summarize its behavior and document its arguments and return values.
  • It should also list all the exceptions that can be raised and other optional arguments.

Example 5: Docstrings for Python functions

 def add_binary(a, b): ''' Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b ''' binary_sum = bin(a+b)(2:) return binary_sum print(add_binary.__doc__)

Output

 Returns the sum of two decimal numbers in binary digits. Parameters: a (int): A decimal integer b (int): Another decimal integer Returns: binary_sum (str): Binary string of the sum of a and b

As you can see, we have included a short description of what the function does, the parameter it takes in and the value it returns. The string literal is embedded to the function add_binary as its __doc__ attribute.

3. Docstrings for Python Classes

  • The docstrings for classes should summarize its behavior and list the public methods and instance variables.
  • The subclasses, constructors, and methods should each have their own docstrings.

Example 6: Docstrings for Python class

Suppose we have a Person.py file with the following code:

 class Person: """ A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age. """ def __init__(self, name, surname, age): """ Constructs all the necessary attributes for the person object. Parameters ---------- name : str first name of the person surname : str family name of the person age : int age of the person """ self.name = name self.surname = surname self.age = age def info(self, additional=""): """ Prints the person's name and age. If the argument 'additional' is passed, then it is appended after the main info. Parameters ---------- additional : str, optional More info to be displayed (default is None) Returns ------- None """ print(f'My name is (self.name) (self.surname). I am (self.age) years old.' + additional)

Here, we can use the following code to access only the docstrings of the Person class:

 print(Person.__doc__)

Output

 A class to represent a person.… Attributes ---------- name : str first name of the person surname : str family name of the person age : int age of the person Methods ------- info(additional=""): Prints the person's name and age

Using the help() Function for Docstrings

We can also use the help() function to read the docstrings associated with various objects.

Example 7: Read Docstrings with the help() function

We can use the help() function on the class Person in Example 6 as:

 help(Person)

Output

 Help on class Person in module __main__: class Person(builtins.object) | Person(name, surname, age) | | A class to represent a person. | |… | | Attributes | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | Methods | ------- | info(additional=""): | Prints the person's name and age. | | Methods defined here: | | __init__(self, name, surname, age) | Constructs all the necessary attributes for the person object. | | Parameters | ---------- | name : str | first name of the person | surname : str | family name of the person | age : int | age of the person | | info(self, additional='') | Prints the person's name and age. | | If the argument 'additional' is passed, then it is appended after the main info. | | Parameters | ---------- | additional : str, optional | More info to be displayed (default is None) | | Returns | ------- | None | | ---------------------------------------------------------------------- | Data descriptors defined here: | | __dict__ | dictionary for instance variables (if defined) | | __weakref__ | list of weak references to the object (if defined)

Here, we can see that the help() function retrieves the docstrings of the Person class along with the methods associated with that class.

4. Docstrings for Python Scripts

  • The docstrings for Python script should document the script's functions and command-line syntax as a usable message.
  • It should serve as a quick reference to all the functions and arguments.

5. Docstrings for Python Packages

The docstrings for a Python package is written in the package's __init__.py file.

  • It should contain all the available modules and sub-packages exported by the package.

Docstring Formats

We can write docstring in many formats like the reStructured text (reST) format, Google format or the NumPy documentation format. To learn more, visit Popular Docstring Formats

Vi kan også generere dokumentasjon fra doktringer ved hjelp av verktøy som Sphinx. For å lære mer, besøk offisiell Sphinx-dokumentasjon

Interessante artikler...