python - python 类 __init__ 函数的 PyCharm 模板

标签 python class attributes pycharm

我有一个带有多个初始化变量的 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 中的设置方式:

enter image description here


或者,您可以更改设置实例属性的方式并将其概括为 N 个参数,请参阅:

关于python - python 类 __init__ 函数的 PyCharm 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40114251/

相关文章:

python - 使用 psycopg2 的内置格式创建动态类型表

class - 在UML类图中,如果B被类A使用的接口(interface)使用,我是否应该绘制从类A到B的依赖关系?

java - 如何将我在第一个类中输入的文本打印到第二堂课?

c++ - 指针地址给出 1 而不是十六进制地址

从另一台服务器下载时 HTML5 下载属性不起作用,即使 Access-Control-Allow-Origin 设置为全部 (*)

python - 使用map和lambda来模拟字典理解

python - tkinter 程序使用 cx_Freeze 编译但程序不会启动

python - 检查函数是否在 try 子句中被调用

c# - 获取枚举值的自定义属性

python - Tensorflow FailedPreconditionError,但所有变量都已初始化