Learning Sections show
Docstrings in Python
Docstrings in Python are string literals that appear right after the definition of a function, method, class, or module. They are used to document the functionality of the code.
Single-Line Docstrings
Single-line docstrings are used for very short descriptions. They fit on one line.
"""This is a single-line docstring."""
# Example of a single-line docstring in a function
def add(a, b):
"""Returns the sum of a and b."""
return a + b
Multi-Line Docstrings
Multi-line docstrings are used for more detailed documentation. They can span multiple lines.
"""This is a multi-line docstring.
It can span multiple lines.
It provides a detailed description of the function, method, class, or module."""
# Example of a multi-line docstring in a function
def subtract(a, b):
"""Return the difference of a and b.
Parameters:
a (int or float): The minuend.
b (int or float): The subtrahend.
Returns:
int or float: The difference between a and b.
"""
return a - b
Accessing Docstrings
Docstrings can be accessed using the __doc__
attribute.
# Accessing docstrings
def multiply(a, b):
"""Return the product of a and b."""
return a * b
print(multiply.__doc__) # Output: Return the product of a and b.
Docstrings for Classes
Docstrings can also be used to document classes and their methods.
# Example of docstrings in a class
class MathOperations:
"""Class for various math operations."""
def __init__(self, value):
"""Initialize with a value."""
self.value = value
def add_to_value(self, addend):
"""Add addend to value and return the result."""
return self.value + addend