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.
The attrs library does something like this.
Maybe this is a closed question, but I would like to propose my solution in order to know what you think about it. I have used a metaclass which applies a decorator to init method
You can use a decorator:
Use it to decorate the
__init__
method:Output:
For Python 3.7+ you can use a Data Class, which is a very pythonic and maintainable way to do what you want.
It allows you to define fields for your class, which are your automatically initialized instance variables.
It would look something like that:
The
__init__
method will already be in your class.Note that here type hinting is required, that is why I have used
int
andstr
in the example. If you don't know the type of your field, you can use Any from thetyping
module.The Data Class has many advantages compared to the proposed solutions:
**kwargs
.namedtuple
.__init__
using the__post_init__
method.Another thing you can do:
But the only solution I would recommend, besides just spelling it out, is "make a macro in your editor" ;-p
Quoting the Zen of Python,