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

标签 python groovy parameters constructor pycharm

我正在使用 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 没有内置 intention action自动声明和设置构造函数签名中的所有实例变量。

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

  1. 使用External tool .
  2. 使用 Live Template变量和函数。
  3. (我想是 a Plugin could be developed,但可能涉及更多工作。)

使用外部工具有其自身的一系列问题,请参阅 PyCharm: Run black -S on region 的答案。了解它涉及的内容。

对于这个问题中的问题,实时模板可能是最容易集成的。主要缺点是必须使用 Groovy Script(实时模板函数列表提供了使用 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());一起发挥作用来自 Predefined functions . (虽然 Groovy 脚本 可以写在一行上,但在这种情况下将它放在外部文件中更容易)。

enter image description here

选择包含缩进的行,复制到剪贴板 (Ctrl + C),然后按 Ctrl + J 选择实时模板

enter image description here

实例变量声明生成(回车后调整缩进)

enter image description here

尾注。

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

关于python - 将所有构造函数参数作为实例属性添加到 PyCharm 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58661996/

相关文章:

c++ - 为什么不从构造函数推断模板参数?

python - 用numpy、python和open cv2.4迭代多维数组

python - TK : How to remove tk entry if the user inputs anything than strings?

javascript - Django json.loads(request.body) 给出错误 Expecting value : line 1 column 1

gradle - gradle bootRun 执行失败

java - 在 Groovy/Java 中比较两个 XML 字符串/文件

python - 在 python 类的 init 函数中使用 pandas fillna

grails - Groovy 在 list.find 调用上给出 NPE,但仅在一段时间之后

c++ - 声明函数参数时如何覆盖所有可能的数据类型?

arrays - 将数组参数直接解压为参数?