PyCharm template for python class __init__ functio

2019-02-10 16:58发布

I have a python class with several init variables:

class Foo(object):
    def __init__(self, d1, d2):
        self.d1 = d1
        self.d2 = d2

Is there a way to create this code automatically in PyCharm, so I don't have to type explicitly:

self.dn = dn

This pattern happens very often in my code. Is there a better (Pythonic) way to initialize classes?

I have already seen this post ( What is the best way to do automatic attribute assignment in Python, and is it a good idea?), but I don't want to use a decorator as it makes the code less readable.

2条回答
Juvenile、少年°
2楼-- · 2019-02-10 17:27

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

enter image description here

查看更多
Juvenile、少年°
3楼-- · 2019-02-10 17:33

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:

enter image description here


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

查看更多
登录 后发表回答