我有一个带有几个初始化变量的python类:

class Foo(object):
    def __init__(self, d1, d2):
        self.d1 = d1
        self.d2 = d2

有没有一种方法可以在PyCharm中自动创建此代码,因此我不必显式键入:
self.dn = dn

这种模式在我的代码中经常发生。有没有更好的(Pythonic)方法来初始化类?

我已经看过这篇文章(What is the best way to do automatic attribute assignment in Python, and is it a good idea?),但是我不想使用装饰器,因为它会使代码的可读性降低。

最佳答案

您可以通过创建自定义Live Template开始。我不确定是否可以通过这种方式自动生成数量可变的参数,但是,对于两个构造函数参数,实时模板可能如下所示:

class $class_name$:
    def __init__(self, $arg1$, $arg2$):
        self.$arg1$ = $arg1$
        self.$arg2$ = $arg2$
$END$

这就是我在PyCharm中设置的方式:

python - python类__init__函数的PyCharm模板-LMLPHP

或者,您可以更改设置实例属性的方式并将其归纳为N个参数,请参见:
  • How can you set class attributes from variable arguments (kwargs) in python
  • 10-04 10:36
    查看更多