我有一个带有多个初始化变量的 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 中的设置方式:
或者,您可以更改设置实例属性的方式并将其概括为 N 个参数,请参阅:
关于python - python 类 __init__ 函数的 PyCharm 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114251/