eshansingh1 eshansingh1 - 1 year ago 60
Python Question

Is there a Python shortcut for an __init__ that simply sets properties?

It's sometimes common in Python to see

code like this:

class SomeClass(object):
def __init__(self, a, b, c, d, e, f, g):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
self.g = g

especially if the class in question is purely a data structure with no behaviour. Is there a (Python 2.7) shortcut for this or a way to make one?

Answer Source

You might find the attrs library helpful. Here's an example from the overview page of the docs:

>>> import attr
>>> @attr.s
... class C(object):
...     x = attr.ib(default=42)
...     y = attr.ib(default=attr.Factory(list))
...     def hard_math(self, z):
...         return self.x * self.y * z
>>> i = C(x=1, y=2)
>>> i
C(x=1, y=2)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download