将所有构造函数参数作为实例属性添加到 PyCharm 中的类中

2024-05-27

我正在使用 PyCharm。我开始定义一个类:

class A:
    def __init__(self,a,b,c):

我希望它看起来像这样:

class A:
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c

使用 alt-enter 我可以让 PyC​​harm 将单个字段添加到类中__init__但随后我必须返回并为每个变量单独执行一次,这最终会变得很烦人。有没有什么捷径可以一次性完成所有这些?


PyCharm 没有内置意图行动 https://www.jetbrains.com/help/pycharm/intention-actions.html自动声明并设置构造函数签名中的所有实例变量。

因此,实现此功能的两个主要替代方案是:

  1. 使用外部工具 https://www.jetbrains.com/help/pycharm/configuring-third-party-tools.html.
  2. Using a 实时模板 https://www.jetbrains.com/help/pycharm/template-variables.html变量和函数。
  3. (我想可以开发一个插件 https://plugins.jetbrains.com/docs/intellij/pycharm.html,但可能会涉及更多工作。)

使用外部工具有其自身的一系列问题,请参阅答案PyCharm:运行black -S在区域上 https://stackoverflow.com/a/67345512了解它所涉及的内容的一般概念。

对于这个问题中的问题,实时模板可能是最容易集成的。主要缺点是必须使用Groovy 脚本(实时模板功能列表提供了使用的可能性RegEx- 我认为前者是更好的方法。)

因此使用以下 Groovy 脚本test.groovy

import java.util.regex.Pattern
import java.util.regex.Matcher

// the_func = "    fun_name(a, b, c)"  // For stand-alone testing.
the_func = _1  // PyCharm clipboard() function argument.

int count_indent = the_func.indexOf(the_func.trim());  // Count indentation whitspaces.

def arg_list_str

def pattern = "\\((.*?)\\)"
Matcher m = Pattern.compile(pattern).matcher(the_func);

while (m.find()) {
    arg_list_str = m.group(1)  // Retrieve parameters from inside parenthesis.
}

// println arg_list_str
String[] arguments = arg_list_str.split(",")  // Splits on parameter separator.

def result = ['\n']  // Ends the constructor line for convenience.

for(arg in arguments) {
    arg = arg.trim()  // Remove whitspaces surrounding parameter.
    if(arg == "self")  // Skips first method parameter 'self'.
        continue
    arg = " ".repeat(count_indent+4) + "self." + arg + " = " + arg + "\n" 
    result.add(arg)
}

String joinedValues = result.join("")

return joinedValues

并将实时模板设置为File > Settings > Editor > Live Templates如屏幕截图所示。使用clipboard()一起发挥作用groovyScript("c:\\dir_to_groovy\\test.groovy", clipboard());来自预定义函数 https://www.jetbrains.com/help/pycharm/template-variables.html#predefined_functions。 (虽然Groovy 脚本可以写在单行上,在这种情况下更容易将其放入外部文件中)。

Selecting the line including indentation, copying to the clipboard (Ctrl + C), and choosing the Live Template pressing Ctrl + J

生成实例变量的声明(按 Enter 后调整缩进。)

结束注释。

包含的签名解析器Groovy 脚本简单化,只关心解决问题中的问题。通过一些研究,可能可以使用完整的签名解析器来处理复杂的类型提示和默认参数。但就示例而言,它可以充分工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将所有构造函数参数作为实例属性添加到 PyCharm 中的类中 的相关文章

随机推荐