如何使 VS Code 自动完成 Python 类属性初始化

问题描述:

我正在将 VS Code 用于 Python 项目.

I'm using VS Code for Python projects.

当我写:

class User:
    def __init__(self, name, age, group=None):

我希望 VS Code 自动完成以下内容:

I want VS Code to autocomplete the following:

class User:
    def __init__(self, name, age, group=None):
        self.name = name
        self.age = age
        self.group = group

这可以用 VS Code 实现吗?我见过其他一些编辑这样做.有扩展吗?非常感谢!

Is this possible with VS Code? I've seen some other editor do this. Is there an extension for this? Thanks a lot!

我制作了一个基于 类的带有属性初始化器的 Python 版本Mark 的 init 片段

  "Class Initializer": {
    "prefix": "cinit",
    "body": [
      "def __init__(self, $1):",
      "${1/([^,=]+)(?:=[^,]+)?(,\\s*|)/\tself.$1 = $1${2:+\n\t}/g}"
    ],
    "description": "Class __init__"
  }

我使用空格来缩进,并且在另一个片段中 \t 被转换为空格.

I use spaces for indenting and in another snippet \t is transformed to spaces.

如果选项卡没有正确展开,请用适当数量的空格替换 \t.(有 2 个 \t).

If the tabs are not expanded properly, substitute \t with the proper number of spaces. (there are 2 \t).

输入类名后: 回车缩进1,然后输入前缀cinit.

After typing class name: Enter you are indented 1, then type the prefix cinit.