Python Docstrings (Dengan Contoh)

Dalam tutorial ini, kita akan belajar mengenai dokstring Python. Lebih khusus lagi, kita akan belajar bagaimana dan mengapa docstring digunakan dengan bantuan contoh.

Python docstrings adalah literal string yang muncul tepat setelah definisi fungsi, kaedah, kelas, atau modul. Mari kita ambil contoh.

Contoh 1: Dokstring

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

Di sini, rentetan literal:

 '' Mengambil angka n, mengembalikan segiempat n '' '

Di dalam tanda petik tiga terdapat dokumentasi fungsi square()seperti yang muncul tepat selepas definisi.

Catatan: Kami juga dapat menggunakan tiga """petikan untuk membuat dokumen.

Komen Python vs Docstrings

Komen Python

Komen adalah penerangan yang membantu pengaturcara memahami maksud dan fungsi program dengan lebih baik. Mereka tidak diendahkan sepenuhnya oleh jurubahasa Python.

Di Python, kami menggunakan simbol hash #untuk menulis komen satu baris. Sebagai contoh,

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

Komen Python Menggunakan Rentetan

Sekiranya kita tidak memberikan rentetan pada pemboleh ubah apa pun, mereka bertindak sebagai komen. Sebagai contoh,

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

Catatan: Kami menggunakan tanda petik tiga untuk rentetan berbilang baris.

Dokstring Python

Seperti yang disebutkan di atas, Pstronstrings adalah string yang digunakan tepat setelah definisi fungsi, metode, kelas, atau modul (seperti dalam Contoh 1 ) Mereka digunakan untuk mendokumentasikan kod kami.

Kita boleh mengakses dokumen ini menggunakan __doc__atribut.

Atribut Python __doc__

Setiap kali literal string hadir tepat setelah definisi fungsi, modul, kelas atau kaedah, mereka dikaitkan dengan objek sebagai __doc__atributnya. Kita kemudian boleh menggunakan atribut ini untuk mendapatkan dokumen ini.

Contoh 2: Mencetak dokumen

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

Pengeluaran

 Mengambil nombor n, mengembalikan kuasa dua n

Di sini, dokumentasi square()fungsi kami dapat diakses menggunakan __doc__atribut.

Sekarang, mari kita lihat dokumen untuk fungsi terbina dalam print():

Contoh 3: Dokstring untuk fungsi cetak () terbina dalam

 print(print.__doc__)

Pengeluaran

cetak (nilai,…, sep = '', end = ' n', file = sys.stdout, flush = False) Mencetak nilai ke aliran, atau ke sys.stdout secara lalai. Hujah kata kunci pilihan: fail: objek seperti fail (aliran); lalai ke sys.stdout semasa. sep: rentetan dimasukkan di antara nilai, ruang lalai. akhir: tali ditambahkan selepas nilai terakhir, lalai garis baru. siram: sama ada mengalirkan arus secara paksa.

Di sini, kita dapat melihat bahawa dokumentasi print()fungsi hadir sebagai __doc__atribut fungsi ini.

Dokstring baris tunggal di Python

Dokstring baris tunggal adalah dokumen yang sesuai dalam satu baris.

Konvensyen standard untuk menulis satu baris dokumen:

  • Walaupun ia berlapis tunggal, kami masih menggunakan tanda kutip tiga di sekitar dokstring ini kerana dapat diperluas dengan mudah kemudian.
  • Petikan penutup berada pada baris yang sama dengan petikan pembuka.
  • Tidak ada garis kosong sama ada sebelum atau selepas penyusun dokumen.
  • Mereka tidak boleh bersifat deskriptif, melainkan harus mengikuti struktur "Lakukan ini, kembalikan itu" yang diakhiri dengan noktah.

Mari kita ambil contoh.

Contoh 4: Tulis satu baris dokumen untuk fungsi

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

Docstrings pelbagai baris di Python

Docstrings pelbagai baris terdiri daripada garis ringkasan seperti docstring satu baris, diikuti oleh baris kosong, diikuti dengan keterangan yang lebih terperinci.

Dokumen PEP 257 memberikan konvensyen standard untuk menulis pelbagai baris dokumen untuk pelbagai objek.

Beberapa telah disenaraikan di bawah:

1. Dokstring untuk Modul Python

  • Dokstring untuk Modul Python harus menyenaraikan semua kelas, fungsi, objek dan pengecualian yang tersedia yang diimport semasa modul diimport.
  • 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

Kami juga dapat menghasilkan dokumentasi dari dokstring menggunakan alat seperti Sphinx. Untuk mengetahui lebih lanjut, lawati Dokumentasi Sphinx Rasmi

Artikel menarik...