【问题标题】:Add all constructor parameters as instance attributes to class in PyCharm将所有构造函数参数作为实例属性添加到 PyCharm 中的类
【发布时间】:2019-11-01 15:39:41
【问题描述】:

我正在使用 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__ 向类中添加一个字段,但随后我必须返回并为每个变量单独再次执行此操作,这最终会很烦人。有没有什么捷径可以一次性搞定?

【问题讨论】:

  • 这是一个很好的问题,但我认为没有选择。主要是因为每当您向__init__ 添加新参数时,PyCharm 都会让您将该参数分配为属性。但它也为您提供了与参数不同的名称属性。我认为一一分配是故意的……

标签: python groovy parameters constructor pycharm


【解决方案1】:

PyCharm 没有内置的 intention action 来自动声明和设置构造函数签名中的所有实例变量。

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

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

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

对于这个问题中的问题,实时模板可能是最容易集成的。主要缺点是必须使用 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() 函数与Predefined functions 中的groovyScript("c:\\dir_to_groovy\\test.groovy", clipboard()); 一起使用。 (虽然 Groovy 脚本 可以写在单行上,但在这种情况下将它放在外部文件中会更容易)。

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

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

尾注。

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

【讨论】:

  • 是否有人创建了完整的签名解析器来处理复杂类型提示和默认参数?
  • @Slazer 我还没有找到。 mypy 可能有这样的解析器。问题是每个 Python 版本的类型提示都发生了巨大变化,目前甚至 PyCharm linter 都没有 100% 正确地分析类型提示。所以维护这样一个不断变化的解析器绝非易事。我写了这个答案作为概念验证,如果你发现集成它的解析器会按照这个答案中的步骤进行。
猜你喜欢
  • 1970-01-01
  • 2020-05-01
  • 1970-01-01
  • 2019-09-29
  • 2019-11-09
  • 2020-08-26
  • 1970-01-01
  • 2017-06-25
  • 2013-01-27
相关资源
最近更新 更多