PyCharm 没有内置意图行动 https://www.jetbrains.com/help/pycharm/intention-actions.html自动声明并设置构造函数签名中的所有实例变量。
因此,实现此功能的两个主要替代方案是:
- 使用外部工具 https://www.jetbrains.com/help/pycharm/configuring-third-party-tools.html.
- Using a 实时模板 https://www.jetbrains.com/help/pycharm/template-variables.html变量和函数。
- (我想可以开发一个插件 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 脚本简单化,只关心解决问题中的问题。通过一些研究,可能可以使用完整的签名解析器来处理复杂的类型提示和默认参数。但就示例而言,它可以充分工作。