How can I generate fields from constructor (__init__) parameters

已回答
Say I have the following code:
class State(object):
    def __init__(self, linearizedGameBoard, width):
        """

        :type linearizedGameBoard: []
        :type width: int
        :rtype : State
        """
        pass

I swear that there used to be a quick action (Alt+Enter) to generate fields from the parameters (e.g. self.width = width). I can find no such action in the refactor or quick action menus. This is a basic feature; there must be a way to do it. How?
1
Well this is odd - it looks like the quick action to generate the field works only if the __init__ function body is not `pass`. If you put any code in the function, it works.
0
I've reproduced the problem. This behavior is new in 2.6 and is an unintended consequence of some other changes we've made.

http://youtrack.jetbrains.com/issue/PY-7527
0

Whats the shortcut now? Alt+Enter doesnt work for me... :/ It only allows me to flip parameters and create docs strings

1

@Ph Woerdehoff, the following kind of works, but will affect the entire file

Define your init arguments like:

```python

class MyClass:

    def __init__(self, arg1, arg2, arg3, arg4):        

```    

Place your cursor over the `arg1` argument (which should be greyed out because of no local use) and hit Alt+Enter, access the sub-menu of "Add field arg1 to class MyClass" and select "Fix all Unused Local problems in this file" to generate all assignment statements.

1

I don't get any item saying ""Fix all Unused Local problems in this file""

0

@Jeff

It is under Remove parameter now:

0

I want to add fields not remove parameters.

0

You can choose Run inspection on...

And then Add field to class

 

1

Thanks, this worked... it's a lot of keystrokes and/or mouse clicks but way better than typing self.parameter1 = parameter1 for each parameter.

0

Is there really no easier way to do this? This is such a basic code completion feature for such a common task. Why does Pycharm not make this easy?

3

请先登录再写评论。