PyCharm-为所有构造函数参数生成字段 [英] PyCharm - generate fields for all constructor parameters

查看:258
本文介绍了PyCharm-为所有构造函数参数生成字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用构造函数定义一个类:

I define a class with constructor:

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

现在,我想为每个构造函数参数声明一个字段,如下所示:

Now I want to declare a field for each constructor parameter, like this:

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

我想自动执行此操作.通过PyCharm的检查,我可以为参数生成字段,但是一次只能生成一个字段(因为未使用 Parameter x的修复程序),这非常烦人.如何同时针对所有参数执行此操作?

I want to do this automatically. PyCharm's inspection allows me to generate fields for the parameters, but only one at a time (as a fix for Parameter x is not used), which is very annoying. How can I do this, for all parameters, simultaneously?

我发现最接近的东西是用于python类__init__函数的PyCharm模板,并且该解决方案不灵活,因为它仅支持固定数量的参数.而且,我觉得这是必须在成熟的IDE中实现的功能,而Idea允许这样做.

The closest thing I found is PyCharm template for python class __init__ function, and the solution is not flexible, since it supports only fixed number of parameters. Moreover, I feel like this is the feature which must be implemented in mature IDE, and Idea allows one to do this.

该帖子还引用了

That post also references What is the best way to do automatic attribute assignment in Python, and is it a good idea?, which discusses autoassign, which seem to have lots of drawbacks.

我的PyCharm版本是2019.1.3 CE.

My PyCharm version is 2019.1.3 CE.

推荐答案

我最近处理这个问题的方法是在函数中编写所有自变量:

The closest I have come to dealing with this is to write all your arguments in the function:

    class Xyz:
        def __init__(a, b, c):

突出显示一个参数,右键单击,然后单击"显示上下文操作"
它应显示"将字段'a'添加到Xyz类",然后单击箭头►
并点击"在...上运行检查"
将检查范围指定为仅该文件或类.
然后,您的类/文件"应出现在检查结果"窗口中,单击下拉箭头并突出显示参数,您应该能够"向Xyz类中添加字段",这将添加所有您选择的那些.

highlight one argument, Right click, then click "Show Context Actions"
it should show "Add field 'a' to Class Xyz" then click the arrow ►
and click "Run Inspection on ..."
Specify the Inspection scope to just that file or class.
Then your Class/File should appear in the inspection results window, click the drop down arrow and highlight the parameters and you should be able to "Add fields to class Xyz" which will add all the ones you select.

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

这篇关于PyCharm-为所有构造函数参数生成字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆