Python3 Comments

In Python, comments do not affect program execution, but they make code easier to read and understand.

Comments in Python include:Single-line commentsandMulti-line comments。


Single-line Comments

In Python, single-line comments use## at the beginning,#All text after the # symbol is treated as a comment and will not be executed by the interpreter.

Example

# This is a comment
print("Hello, World!")
# This is also a comment

Multi-line Comments

In Python, multi-line strings (text blocks enclosed by three single quotes'''or three double quotes""") can be used as multi-line comments.

1. Using three single quotes

Example

#!/usr/bin/python3

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

print("Hello, World!")

2. Using three double quotes

Example

#!/usr/bin/python3

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

print("Hello, World!")

Note: Although multi-line strings are used here as multi-line comments, they are actually strings. As long as we don't use them, they won't affect the running of the program.

These strings can be placed in some positions in the code without being actually executed, thus achieving the effect of comments.

Notes on Multi-line Comments

In Python, multi-line comments are defined by three single quotes'''or three double quotes"""to define,This type of comment cannot be nested.。

When you start a multi-line comment block, Python will treat all subsequent lines as comments until it encounters another set of three single quotes or three double quotes.

Nesting multi-line comments will cause syntax errors:

Example (Incorrect)

'''
This is the outer multi-line comment
It can contain some descriptive content

    '''

This is an attempt to nest a multi-line comment
It will cause a syntax error
    '''
'''

In this example, the inner three single quotes are not correctly recognized as the end of the multi-line comment, but are interpreted as an ordinary string, which will lead to incorrect code structure.

Correct approach: use single-line comments for nesting

Example (Correct)

'''
This is the outer multi-line comment
It can contain some descriptive content

# This is an inner single-line comment
# It can be nested inside a multi-line comment
'''


Docstring (Documentation Strings)

Python's Docstring (documentation string) is a special comment used to add documentation to functions, classes, modules, etc. It is similar to Java's Javadoc, but more powerful and flexible.

Unlike ordinary comments,Docstrings can be accessed directly through the__doc____doc__ attribute,or you can use thehelp()help() function to view.

Basic Syntax

Docstrings use three double quotes"""or three single quotes'''to enclose them, and are placed at the beginning of a function, class, or module.

Example

def add(a, b):
    """Return the sum of two numbers"""
    return a + b

# Access via the __doc__ attribute
print(add.__doc__)  # Output: Return the sum of two numbers

Using help() to View Documentation

Example

def add(a, b):
    """Return the sum of two numbers"""
    return a + b

# Use the help() function
help(add)

Expected output:

Help on function add in module __main__:

add(a, b)
    返回两数之和

Using the inspect Module to Extract Documentation

Python's standard library provides theinspectinspect module, which can directly extract documentation content:

Example

import inspect

def add(a, b):
    """Return the sum of two numbers"""
    return a + b

# Use inspect.getdoc() to get the documentation
print(inspect.getdoc(add))  # Output: Return the sum of two numbers

Expected output:

Return the sum of two numbers

Multi-line Docstring

For complex functions, you can use multi-line Docstrings:

Example

def calculate(a, b, operation="add"):
    """
Perform mathematical operations

Parameters:
a: The first number
b: The second number
operation: The operation type, optional "add", "subtract", "multiply"

Returns:
The calculation result
    """

    if operation == "add":
        return a + b
    elif operation == "subtract":
        return a - b
    elif operation == "multiply":
        return a * b
    else:
        raise ValueError("Unsupported operation")

# View the full documentation
help(calculate)

Expected output:

Help on function calculate in module __main__:

calculate(a, b, operation='add')
    执行数学运算

    Arguments:
        a: 第一个数字
        b: 第二个数字
        operation: 操作类型,可选 "add", "subtract", "multiply"

    返回:
        计算结果

Class Docstring

Docstrings can also be used for classes:

Example

class Person:
    """Person class, used to represent a person's basic information"""

    def __init__(self, name, age):
        """
Initialize a person object

Parameters:
name: Name
age: Age
        """

        self.name = name
        self.age = age

    def introduce(self):
        """Introduce this person"""
        return f"My name is {self.name}, and I am {self.age} years old"

# Access the class documentation
print(Person.__doc__)

# Access the method documentation
print(Person.introduce.__doc__)

Expected output:

Person class, used to represent basic information about a person
Introduce this person

Docstring Conventions

There are several Docstring styles in Python. Common ones include:

  • Google style: Uses spaces for indentation, with clear labels for parameters and return values.
  • Sphinx/reST style: Uses a colon at the beginning, such as:param name:。
  • NumPy style: Similar to Google style, but with slightly different formatting.

It is recommended to choose one style in your project and keep it consistent.

Other extensions