Automatically initialize instance variables?

2019-01-03 08:22发布

I have a python class that looks like this:

class Process:
    def __init__(self, PID, PPID, cmd, FDs, reachable, user):

followed by:

        self.PID=PID
        self.PPID=PPID
        self.cmd=cmd
        ...

Is there any way to autoinitialize these instance variables, like C++'s initialization list? It would spare lots of redundant code.

14条回答
该账号已被封号
2楼-- · 2019-01-03 08:49

You could do it easily with the keyword arguments, e.g. like this:

>>> class D:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

>>> D(test='d').test
'd'

similar implementation for the positional arguments would be:

>> class C:
    def __init__(self, *args):
        self.t, self.d = args


>>> C('abc', 'def').t
'abc'
>>> C('abc', 'def').d
'def'

which to me doesn't seem to solve your problem.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-03 08:49

nu11ptr has made a small module, PyInstanceVars, which includes this functionality as a function decorator. In the module's README is states that the "[...] performance is now only 30-40% worse than explicit initialization under CPython".

Usage example, lifted straight from the module's documentation:

>>> from instancevars import *
>>> class TestMe(object):
...     @instancevars(omit=['arg2_'])
...     def __init__(self, _arg1, arg2_, arg3='test'):
...             self.arg2 = arg2_ + 1
...
>>> testme = TestMe(1, 2)
>>> testme._arg1
1
>>> testme.arg2_
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'TestMe' object has no attribute 'arg2_'
>>> testme.arg2
3
>>> testme.arg3
'test'
查看更多
登录 后发表回答