Reputation: 958
I'm using VS Code for Python projects.
When I write:
class User:
def __init__(self, name, age, group=None):
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
Is this possible with VS Code? I've seen some other editor do this. Is there an extension for this? Thanks a lot!
Upvotes: 5
Views: 8786
Reputation: 1
May be you had saved the class file in another folder. Because I am working in vs code with python language and now i am trying to learn objects and class and I am also facing the problem that my class in not initiating. Then I saved my class file in same folder and now the problem is solved.
Upvotes: 0
Reputation: 83
I was trying to do the same thing, found your answer, implemented it and since I'm learning Regex, though it would be nice to try to generalize for atribute typing. Came up with the following:
"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"
}
The sequence is:
$1
- Class name (also fills default docstring)
$2
- Inheritance (need to type in the parentheses. Here I wanted to set them as default, and remove it if empty. I know it still works with empty parentheses, but I couldn't make it delete if empty and not typed inside $4
)
$3
- Class description
$4
- Attribute declaration, including typing following the syntax in Support for type hints
Example:
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
Upvotes: 1
Reputation: 28623
I have made a Python version with attribute initializers based on the class init snippet by Mark
"Class Initializer": {
"prefix": "cinit",
"body": [
"def __init__(self, $1):",
"${1/([^,=]+)(?:=[^,]+)?(,\\s*|)/\tself.$1 = $1${2:+\n\t}/g}"
],
"description": "Class __init__"
}
I use spaces for indenting and in another snippet \t
is transformed to spaces.
If the tabs are not expanded properly, substitute \t
with the proper number of spaces. (there are 2 \t
).
After typing class name:
Enter you are indented 1, then type the prefix cinit
.
Upvotes: 5