PyCharm template for python class __init__ function

前端 未结 3 534
忘掉有多难
忘掉有多难 2020-12-16 05:16

I have a python class with several init variables:

class Foo(object):
    def __init__(self, d1, d2):
        self.d1 = d1
        self.d2 = d2
相关标签:
3条回答
  • 2020-12-16 05:47

    Partially answering my own question:

    Very handy thank you. In version 2020.2 the "Fix all" option is gone. Anyone knows how to add it back?

    I haven't found a way to add the missing option back, but a workaround that will accomplish the same, adding all missing fields to the class.

    The answer comes from this post: https://stackoverflow.com/a/62060345/1067293

    • Place the mouse cursor over an unused argument and hit Alt+Enter.
    • Then hit the right arrow and select "Run inspection on..."

    • On the new floating window select the file scope.

    • The inspection panel will appear on the bottom.
    • On the left select the file.
    • Then on the right, click the "Add field to class" button.

    It's a little bit too elaborate, but nonetheless comes in handy when you've more than a few args.

    0 讨论(0)
  • 2020-12-16 05:48

    You can start by making a custom Live Template. I'm not sure about whether you can auto-generate variable number of arguments this way, but, for two constructor arguments the live template may look like:

    class $class_name$:
        def __init__(self, $arg1$, $arg2$):
            self.$arg1$ = $arg1$
            self.$arg2$ = $arg2$
    $END$
    

    This is how I've set it up in PyCharm:


    Or, you can change the way you set the instance attributes and generalize it for N arguments, see:

    • How can you set class attributes from variable arguments (kwargs) in python
    0 讨论(0)
  • 2020-12-16 06:02

    I learned of another way to solve this.

    • Move cursor to argument
    • Press alt + enter
    • Select Add field '[arg]' to class for single arg -or-
    • Press right arrow key to open sub menu
    • Select Fix all 'unused local' problems to add all args

    0 讨论(0)
提交回复
热议问题