Home Backend Development Python Tutorial Parsing Python code comment specification code

Parsing Python code comment specification code

Aug 15, 2020 pm 05:18 PM
python Code comments specification

Parsing Python code comment specification code

##1. Introduction to code comments

    Comments are explanations and explanations of the code, and their purpose is to make it easier for people to understand the code.
  • Comments are when the programmer writes an explanation or hint for a statement, program segment, function, etc., which can improve the readability of the program code.
  • In codes with processing logic, the amount of effective comments in the source program must be more than 20%.

Relevant learning recommendations:

python video tutorial

2. Code comment classification

Line comment: The line after the symbol will not be compiled (displayed)


Block comment: The part in the middle of the block comment symbol will not be compiled Compile


3. Basics of python code comments

# is used in Python to represent single-line comments. Single-line comments can be placed as a separate line above the line of code being commented, or after a statement or expression. The following example:


name = 'xiaohong' # Single line comment

# Single line comment

name = 'xiaohong'

Use three single quotes or three double quotes in Python to indicate multi-line comments. Used when there are too many comments to write, as in the following example:


'''

This is a multi-line comment using three single quotes
'''

"""

This is a multi-line comment using three double quotes
"""

4. Introduction and use of DocStrings

4.1 Introduction to DocStrings


Document string


is an important tool for interpreting documentation programs. Help your program documentation to be simpler and easier to understand

4.2 Using DocStrings in Python


Use a pair of three single quotes''' or a pair of three in the first line of the function body Double quotes """ to define the docstring. You can use doc (note the double underscore) to call the docstring attribute in the function.

Writing example is as follows:

def add(num1,num2):
  """ 完成传入的两个数之和

  :param num1: 加数1
  :param num2: 加数2
  :return: 和
  """
  return num1 + num2

print( add.__doc__ )

Remarks: DocStrings Document string usage convention: Its first line briefly describes the function function, the second line is blank, and the third line is a specific description of the function.

5. Common writing styles of DocStrings

5.1 reST style


This is a popular style now, reST style, the royal format of Sphinx, which is relatively compact.

"""
This is a reST style.

:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""

5.2 Google style

"""
This is a groups style docs.

Parameters:
 param1 - this is the first param
 param2 - this is a second param

Returns:
 This is a description of what is returned

Raises:
 KeyError - raises an exception
"""

5.3 Numpydoc (Numpy style)

"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.

Parameters
----------
first : array_like
 the 1st param name `first`
second :
 the 2nd param
third : {'value', 'other'}, optional
 the 3rd param, by default 'value'

Returns
-------
string
 a value in a string

Raises
------
KeyError
 when a key error
OtherError
 when an other error
"""

6. Some annotation experience

    The more comments, the better. For code that is clear at a glance, there is no need to add comments.
  • For complex operations, corresponding comments should be written before the operation starts.
  • For code that is not clear at a glance , comments should be added after the code.
  • Never describe the code. Generally, people who read the code know the syntax of Python, but they just don’t know what the code is doing
Related learning Recommended:

Programming Video

The above is the detailed content of Parsing Python code comment specification code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Peak: How To Revive Players
1 months ago By DDD
PEAK How to Emote
4 weeks ago By Jack chen

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

Python for loop over a tuple Python for loop over a tuple Jul 13, 2025 am 02:55 AM

In Python, the method of traversing tuples with for loops includes directly iterating over elements, getting indexes and elements at the same time, and processing nested tuples. 1. Use the for loop directly to access each element in sequence without managing the index; 2. Use enumerate() to get the index and value at the same time. The default index is 0, and the start parameter can also be specified; 3. Nested tuples can be unpacked in the loop, but it is necessary to ensure that the subtuple structure is consistent, otherwise an unpacking error will be raised; in addition, the tuple is immutable and the content cannot be modified in the loop. Unwanted values can be ignored by \_. It is recommended to check whether the tuple is empty before traversing to avoid errors.

What is a pure function in Python What is a pure function in Python Jul 14, 2025 am 12:18 AM

Pure functions in Python refer to functions that always return the same output with no side effects given the same input. Its characteristics include: 1. Determinism, that is, the same input always produces the same output; 2. No side effects, that is, no external variables, no input data, and no interaction with the outside world. For example, defadd(a,b):returna b is a pure function because no matter how many times add(2,3) is called, it always returns 5 without changing other content in the program. In contrast, functions that modify global variables or change input parameters are non-pure functions. The advantages of pure functions are: easier to test, more suitable for concurrent execution, cache results to improve performance, and can be well matched with functional programming tools such as map() and filter().

How to prevent a method from being overridden in Python? How to prevent a method from being overridden in Python? Jul 13, 2025 am 02:56 AM

In Python, although there is no built-in final keyword, it can simulate unsurpassable methods through name rewriting, runtime exceptions, decorators, etc. 1. Use double underscore prefix to trigger name rewriting, making it difficult for subclasses to overwrite methods; 2. judge the caller type in the method and throw an exception to prevent subclass redefinition; 3. Use a custom decorator to mark the method as final, and check it in combination with metaclass or class decorator; 4. The behavior can be encapsulated as property attributes to reduce the possibility of being modified. These methods provide varying degrees of protection, but none of them completely restrict the coverage behavior.

Can a Python class have multiple constructors? Can a Python class have multiple constructors? Jul 15, 2025 am 02:54 AM

Yes,aPythonclasscanhavemultipleconstructorsthroughalternativetechniques.1.Usedefaultargumentsinthe__init__methodtoallowflexibleinitializationwithvaryingnumbersofparameters.2.Defineclassmethodsasalternativeconstructorsforclearerandscalableobjectcreati

what is if else in python what is if else in python Jul 13, 2025 am 02:48 AM

ifelse is the infrastructure used in Python for conditional judgment, and different code blocks are executed through the authenticity of the condition. It supports the use of elif to add branches when multi-condition judgment, and indentation is the syntax key; if num=15, the program outputs "this number is greater than 10"; if the assignment logic is required, ternary operators such as status="adult"ifage>=18else"minor" can be used. 1. Ifelse selects the execution path according to the true or false conditions; 2. Elif can add multiple condition branches; 3. Indentation determines the code's ownership, errors will lead to exceptions; 4. The ternary operator is suitable for simple assignment scenarios.

Python for loop range Python for loop range Jul 14, 2025 am 02:47 AM

In Python, using a for loop with the range() function is a common way to control the number of loops. 1. Use when you know the number of loops or need to access elements by index; 2. Range(stop) from 0 to stop-1, range(start,stop) from start to stop-1, range(start,stop) adds step size; 3. Note that range does not contain the end value, and returns iterable objects instead of lists in Python 3; 4. You can convert to a list through list(range()), and use negative step size in reverse order.

Accessing data from a web API in Python Accessing data from a web API in Python Jul 16, 2025 am 04:52 AM

The key to using Python to call WebAPI to obtain data is to master the basic processes and common tools. 1. Using requests to initiate HTTP requests is the most direct way. Use the get method to obtain the response and use json() to parse the data; 2. For APIs that need authentication, you can add tokens or keys through headers; 3. You need to check the response status code, it is recommended to use response.raise_for_status() to automatically handle exceptions; 4. Facing the paging interface, you can request different pages in turn and add delays to avoid frequency limitations; 5. When processing the returned JSON data, you need to extract information according to the structure, and complex data can be converted to Data

See all articles