python类__init__函数的PyCharm模板 [英] PyCharm template for python class __init__ function

查看:445
本文介绍了python类__init__函数的PyCharm模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有几个初始化变量的python类:

I have a python class with several init variables:

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

有没有一种方法可以在PyCharm中自动创建此代码,因此不必显式键入:

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

self.dn = dn

这种模式在我的代码中经常发生.有没有更好的(Pythonic)方法来初始化类?

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.

推荐答案

您可以先创建自定义

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$

这是我在PyCharm中设置的方式:

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

或者,您可以更改设置实例属性的方式并将其归纳为N个参数,请参见:

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

这篇关于python类__init__函数的PyCharm模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆