【问题标题】:PyCharm - generate fields for all constructor parametersPyCharm - 为所有构造函数参数生成字段
【发布时间】:2019-11-09 22:35:30
【问题描述】:

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

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

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

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

我想自动执行此操作。 PyCharm 的检查允许我为参数生成字段,但一次只能生成一个(作为Parameter x is not used 的修复),这很烦人。我怎样才能同时为所有参数执行此操作?

我找到的最接近的东西是PyCharm template for python class __init__ function,解决方案不灵活,因为它只支持固定数量的参数。而且,我觉得这是成熟IDE中必须实现的功能,Idea允许这样做。

该帖子还引用了What is the best way to do automatic attribute assignment in Python, and is it a good idea?,其中讨论了autoassign,这似乎有很多缺点。

我的 PyCharm 版本是 2019.1.3 CE。

【问题讨论】:

标签: python pycharm code-generation


【解决方案1】:

我最接近的处理方法是将所有参数写在函数中:

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

突出显示一个参数,右键单击,然后单击“显示上下文操作
它应该显示“将字段 'a' 添加到 Xyz 类”,然后单击箭头 ►
并点击“Run Inspection on ...
仅将检查范围指定到该文件或类。
然后您的类/文件应该出现在检查结果窗口中,单击下拉箭头并突出显示参数,您应该能够“Add fields to class Xyz”这将添加all 你选择的那些。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-23
    • 2019-09-25
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多