【问题标题】:How to make VS Code Autocomplete Python Class Attribute Initialization如何使 VS Code 自动完成 Python 类属性初始化
【发布时间】:2020-08-04 18:57:06
【问题描述】:

我正在为 Python 项目使用 VS Code。

当我写作时:

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

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

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

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

【问题讨论】:

标签: visual-studio-code vscode-settings


【解决方案1】:

我制作了一个基于class init snippet by Mark 的带有属性初始化器的 Python 版本

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

我使用空格进行缩进,在另一个 sn-p \t 中转换为空格。

如果选项卡未正确展开,请将\t 替换为适当数量的空格。 (有 2 个\t)。

输入class name:Enter你是缩进1,然后输入前缀cinit

【讨论】:

    【解决方案2】:

    我试图做同样的事情,找到了你的答案,实现了它,因为我正在学习正则表达式,尽管尝试概括属性输入会很好。想出了以下几点:

    "Class Defininition": {
        "prefix": "clss",
        "body": [
            "class ${1:ClassName}${2/[(][)]/$1/g}:",
            "\t'''\n\tClass $1: $3\n\t'''\n",
            "\tdef __init__(self, ${4/([^self \\s]*|)/$1/g}):",
            "\t\t${4/(^\\w+|(?<=,\\s)\\w+)(.*?,\\s|:.*|=.*|$)/self.$1 = $1${4:\n\t\t}/g}",
            "\t\t$0"
        ],
        "description": "Initialize Class"
    }
    

    顺序是:

    $1 - 类名(也填写默认文档字符串)

    $2 - 继承(需要输入括号。这里我想将它们设置为默认值,如果为空则将其删除。我知道它仍然适用于空括号,但如果为空我无法将其删除并且没有在$4中输入)

    $3 - 类描述

    $4 - 属性声明,包括按照Support for type hints 中的语法键入

    例子:

    class ClassName:
        '''
        Class ClassName: 
        '''
    
        def __init__(self, foo, bar: int, baz, default=10):
            self.foo = foo
            self.bar = bar
            self.baz = baz
            self.default = default
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-07
      • 1970-01-01
      • 2017-09-29
      • 2021-10-30
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      相关资源
      最近更新 更多