Структури Python (з прикладами)

У цьому навчальному посібнику ми дізнаємося про доктринг Python. Більш конкретно, ми дізнаємось, як і чому використовуються текстові рядки, за допомогою прикладів.

Доктринг Python - це рядкові літерали, які з’являються відразу після визначення функції, методу, класу або модуля. Візьмемо приклад.

Приклад 1: Документи

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

Тут літеральний рядок:

 '' 'Бере число n, повертає квадрат n' ''

Всередині потрійних лапок знаходиться документ документації функції, square()як вона з'являється відразу після її визначення.

Примітка: Ми також можемо використовувати потрійні """лапки для створення рядків документа.

Коментарі Python проти Docstrings

Коментарі Python

Коментарі - це описи, які допомагають програмістам краще зрозуміти намір та функціональність програми. Вони повністю ігноруються інтерпретатором Python.

У Python ми використовуємо хеш-символ #для написання однорядкового коментаря. Наприклад,

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

Коментарі Python за допомогою рядків

Якщо ми не призначаємо рядки жодній змінній, вони виступають як коментарі. Наприклад,

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

Примітка: Ми використовуємо потрійні лапки для багаторядкових рядків.

Структури Python

Як уже згадувалося вище, Python docstrings - це рядки, що використовуються відразу після визначення функції, методу, класу або модуля (як у прикладі 1 ). Вони використовуються для документування нашого коду.

Ми можемо отримати доступ до цих рядків документа, використовуючи __doc__атрибут.

Python __doc__ атрибут

Всякий раз, коли рядкові літерали присутні відразу після визначення функції, модуля, класу чи методу, вони асоціюються з об’єктом як їх __doc__атрибут. Пізніше ми можемо використовувати цей атрибут для отримання цієї документації.

Приклад 2: Друк документації

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

Вихідні дані

 Бере число n, повертає квадрат n

Тут square()можна отримати доступ до документації нашої функції за допомогою __doc__атрибута.

Тепер давайте розглянемо рядки документації для вбудованої функції print():

Приклад 3: Документи для вбудованої функції print ()

 print(print.__doc__)

Вихідні дані

print (value,…, sep = '', end = ' n', file = sys.stdout, flush = False) Друкує значення в потоці або за умовчанням у sys.stdout. Необов’язкові аргументи ключового слова: файл: файлоподібний об’єкт (потік); за замовчуванням поточний sys.stdout. sep: рядок, вставлений між значеннями, за промовчанням пробіл. end: рядок, доданий після останнього значення, за замовчуванням новий рядок. флеш: чи примусово промивати потік.

Тут ми бачимо, що документація print()функції присутня як __doc__атрибут цієї функції.

Однорядні документи у Python

Однорядкові документи - це документи, які вміщуються в один рядок.

Стандартні домовленості для написання однорядкових документальних рядків:

  • Незважаючи на те, що вони однорядкові, ми все одно використовуємо потрійні лапки навколо цих рядків, оскільки їх можна легко розширити пізніше.
  • Закриваючі котирування знаходяться в тому ж рядку, що і початкові котирування.
  • Немає порожнього рядка ні до, ні після документальної стрічки.
  • Вони не повинні бути описовими, навпаки, вони повинні слідувати структурі "Зроби це, поверни те", яка закінчується крапкою.

Візьмемо приклад.

Приклад 4: Напишіть однорядкові документи для функції

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

Багаторядні документи у Python

Багаторядні документальні рядки складаються з підсумкового рядка так само, як однорядковий документальний документ, за яким слідує порожній рядок, за яким слід більш детальний опис.

Документ PEP 257 надає стандартні домовленості щодо написання багаторядної документації для різних об'єктів.

Деякі з них були перелічені нижче:

1. Документи для модулів Python

  • У рядках документації для модулів Python повинні бути перелічені всі доступні класи, функції, об'єкти та винятки, які імпортуються під час імпортування модуля.
  • 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

Ми також можемо генерувати документацію з текстових рядків, використовуючи такі інструменти, як Sphinx. Щоб дізнатись більше, відвідайте офіційну документацію щодо сфінкса

Цікаві статті...