Python Docstrings (Có ví dụ)

Trong hướng dẫn này, chúng ta sẽ tìm hiểu về Python docstrings. Cụ thể hơn, chúng ta sẽ tìm hiểu cách thức và lý do tại sao docstrings được sử dụng với sự trợ giúp của các ví dụ.

Python docstrings là các chuỗi ký tự xuất hiện ngay sau định nghĩa của một hàm, phương thức, lớp hoặc mô-đun. Hãy lấy một ví dụ.

Ví dụ 1: Docstrings

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

Đây, chuỗi ký tự:

 '' 'Lấy một số n, trả về bình phương của n' ''

Bên trong dấu ngoặc kép ba là docstring của hàm square()như nó xuất hiện ngay sau khi định nghĩa của nó.

Lưu ý: Chúng tôi cũng có thể sử dụng ba """trích dẫn để tạo docstrings.

Nhận xét Python so với Docstrings

Nhận xét Python

Nhận xét là mô tả giúp người lập trình hiểu rõ hơn về mục đích và chức năng của chương trình. Chúng hoàn toàn bị trình thông dịch Python bỏ qua.

Trong Python, chúng tôi sử dụng biểu tượng băm #để viết nhận xét một dòng. Ví dụ,

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

Nhận xét Python bằng chuỗi

Nếu chúng ta không gán chuỗi cho bất kỳ biến nào, chúng sẽ hoạt động như các chú thích. Ví dụ,

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

Lưu ý: Chúng tôi sử dụng dấu ngoặc kép ba cho chuỗi nhiều dòng.

Python docstrings

Như đã đề cập ở trên, các chuỗi doc trong Python là các chuỗi được sử dụng ngay sau định nghĩa của một hàm, phương thức, lớp hoặc mô-đun (như trong Ví dụ 1 ). Chúng được sử dụng để ghi lại mã của chúng tôi.

Chúng tôi có thể truy cập các docstrings này bằng cách sử dụng __doc__thuộc tính.

Thuộc tính __doc__ trong Python

Bất cứ khi nào các ký tự chuỗi có mặt ngay sau định nghĩa của một hàm, mô-đun, lớp hoặc phương thức, chúng được liên kết với đối tượng làm __doc__thuộc tính của chúng . Sau đó, chúng tôi có thể sử dụng thuộc tính này để truy xuất chuỗi tài liệu này.

Ví dụ 2: In chuỗi tài liệu

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

Đầu ra

 Lấy một số n, trả về bình phương của n

Tại đây, bạn square()có thể truy cập tài liệu về hàm của chúng tôi bằng cách sử dụng __doc__thuộc tính.

Bây giờ, hãy xem docstrings cho hàm tích hợp print():

Ví dụ 3: Các chuỗi tài liệu cho hàm print () tích hợp sẵn

 print(print.__doc__)

Đầu ra

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) In các giá trị vào một luồng hoặc đến sys.stdout theo mặc định. Các đối số từ khóa tùy chọn: tệp: một đối tượng giống tệp (luồng); mặc định thành sys.stdout hiện tại. sep: chuỗi được chèn giữa các giá trị, mặc định là khoảng trắng. end: chuỗi được nối sau giá trị cuối cùng, mặc định là dòng mới. tuôn ra: có buộc xả dòng không.

Ở đây, chúng ta có thể thấy rằng tài liệu của print()hàm hiện diện dưới dạng __doc__thuộc tính của hàm này.

Docstrings một dòng trong Python

Docstrings đơn dòng là các tài liệu nằm gọn trong một dòng.

Các quy ước tiêu chuẩn để viết docstrings một dòng:

  • Mặc dù chúng được xếp một hàng, chúng tôi vẫn sử dụng dấu ngoặc kép xung quanh các chuỗi tài liệu này vì chúng có thể được mở rộng dễ dàng sau này.
  • Dấu ngoặc kép đóng cùng dòng với dấu ngoặc kép mở đầu.
  • Không có dòng trống trước hoặc sau chuỗi doc.
  • Chúng không nên mang tính mô tả, thay vào đó chúng phải tuân theo cấu trúc "Làm cái này, trả lại cái kia" kết thúc bằng dấu chấm.

Hãy lấy một ví dụ.

Ví dụ 4: Viết docstrings một dòng cho một hàm

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

Docstrings nhiều dòng trong Python

Chuỗi tài liệu nhiều dòng bao gồm một dòng tóm tắt giống như chuỗi tài liệu một dòng, theo sau là một dòng trống, tiếp theo là mô tả chi tiết hơn.

Tài liệu PEP 257 cung cấp các quy ước tiêu chuẩn để viết chuỗi tài liệu nhiều dòng cho các đối tượng khác nhau.

Một số đã được liệt kê dưới đây:

1. Docstrings cho mô-đun Python

  • Các docstrings cho Mô-đun Python phải liệt kê tất cả các lớp, hàm, đối tượng và ngoại lệ có sẵn được nhập khi mô-đun được nhập.
  • 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

Chúng tôi cũng có thể tạo tài liệu từ docstrings bằng các công cụ như Sphinx. Để tìm hiểu thêm, hãy truy cập Tài liệu chính thức về Sphinx

thú vị bài viết...