python注释格式总结

三个双引号的用于文件,类,函数注释。  没有统一的规定,以下是比较清晰的写法。

文件注释(文件顶部):文件用途+空行+作者信息(每行一个键:值)

类注释(类名下行):类用途+空行

                +属性:+回车tab+属性名(属性类型):属性描述     +空行

                +方法:+回车tab+方法名(参数):方法描述

函数注释(函数名下行):函数用途+空行

                                           +参数:+回车tab+参数名(参数类型):参数描述   +空行

                                           +返回值:+回车tab+返回类型:返回值描述  +空行

                                           +Raises(可无): +回车tab+异常类型:异常描述

 

1. 文件注释

文件注释通常放在文件的顶部,用于说明文件的用途、作者信息和其他基本信息

"""
This module provides utility functions for data processing.

Author: John Doe
Email: john.doe@example.com
Date: 2025-01-22
"""

import os
import numpy as np

2. 类注释

类的注释用于说明类的功能、用途以及主要属性和方法

class MyClass:
    """
    This class represents a simple example of a Python class.

    Attributes:
        attr1 (str): 属性1的描述
        attr2 (int): 属性2的描述

    Methods:
        method1(): 方法1的描述
        method2(param): 方法2的描述
    """
    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

3. 函数注释

  • 使用三引号 """
  • 包括以下部分:
    • 简要描述:函数的总体用途。
    • Args:列出所有参数及其描述。
    • Returns:返回值及其类型。
    • Raises(可选):列出可能引发的异常。
def add_numbers(a: int, b: int) -> int:
    """
    Adds two numbers and returns the result.

    Args:
        a (int): The first number.
        b (int): The second number.

    Returns:
        int: The sum of the two numbers.

    Raises:
        ValueError: If the input values are not integers.
    """
    if not isinstance(a, int) or not isinstance(b, int):
        raise ValueError("Both inputs must be integers.")
    return a + b

4. 单行注释

x = 42  # This is the answer to life, the universe, and everything

5. 设置pycharm自动注释

对于文件注释和函数注释,pycharm设置中有直接的相应设置。而对于类注释,需要使用pycharm设置中的live templates间接实现,同理也可以用于实现文件注释和函数注释。

文件注释

相当于是给对应格式的文件添加的,比如说python文件。所以其设置在文件和代码模板中,设置方法如下,ctrl+alt+s打开设置界面。

"""
This module provides ______________

Author: ${USER}
Email: 1345314460@qq.com
Date: ${YEAR}-${MONTH}-${DAY}
"""

之后新建文件的时候注意不要选file, 要选Python File如下图。

类注释

live templates说白了就是根据你的缩写(abbreviation) 以及你设置的展开触发键(Expand with), 进行展开为相应的内容(Template text).

还是通过ctrl+alt+s打开设置界面

"""
   This class _______

   Attributes:
       attr1 (str): 属性1的描述

   Methods:
       method1(param): 方法1的描述
"""

实际上,缩写写成"""class不能被激活,可能是因为"""表示注释,这一部分就不被解析了。经测试""class比较方便,所以这里写为""class, 其他和上图保持一致。之后点击define后勾选python下的class就只能在class范围激活.

测试一下,输入""class, 点击回车或tab键即可自动补全。注意写template text的时候,不要有多余的缩进空格。

 

函数注释

函数注释不再是一个文件对应的模板,其设置方法有所不同。在设置界面中,tool下的python integrated tools中。 

之后写完函数后,在函数名下边,打三个双引号回车就会自动补全。

 

over~

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值