问题
I define a class with constructor:
class Example:
def __init__(self, a, b, c):
...
Now I want to declare a field for each constructor parameter, like this:
class Example:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
I want to do this automatically. PyCharm's inspection allows me to generate fields for the parameters, but only one at a time (as a fix for Parameter x is not used
), which is very annoying. How can I do this, for all parameters, simultaneously?
The closest thing I found is PyCharm template for python class __init__ function, and the solution is not flexible, since it supports only fixed number of parameters. Moreover, I feel like this is the feature which must be implemented in mature IDE, and Idea allows one to do this.
That post also references What is the best way to do automatic attribute assignment in Python, and is it a good idea?, which discusses autoassign
, which seem to have lots of drawbacks.
My PyCharm version is 2019.1.3 CE.
回答1:
The closest I have come to dealing with this is to write all your arguments in the function:
class Xyz:
def __init__(a, b, c):
highlight one argument, Right click, then click "Show Context Actions"
it should show "Add field 'a' to Class Xyz" then click the arrow ►
and click "Run Inspection on ..."
Specify the Inspection scope to just that file or class.
Then your Class/File should appear in the inspection results window, click the drop down arrow and highlight the parameters and you should be able to "Add fields to class Xyz" which will add all the ones you select.
class Xyz:
def __init__(a, b, c):
self.a = a
self.b = b
self.c = c
来源:https://stackoverflow.com/questions/56798926/pycharm-generate-fields-for-all-constructor-parameters