Search code examples
pythonpython-2.7classshortcut

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


It's sometimes common in Python to see __init__ 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?


Solution

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

    >>> import attr
    >>> @attr.s
    ... class SomeClass(object):
    ...     a_number = attr.ib(default=42)
    ...     list_of_numbers = attr.ib(factory=list)
    ...
    ...     def hard_math(self, another_number):
    ...         return self.a_number + sum(self.list_of_numbers) * another_number
    >>> sc = SomeClass(1, [1, 2, 3])
    >>> sc
    SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
    >>> sc.hard_math(3)
    19
    

    If you were using Python 3.8+, you could use dataclasses.

    >>> from typing import List
    >>> from dataclasses import dataclass, field
    >>> @dataclass
    ... class OtherClass:
    ...     a_number: int=42
    ...     list_of_numbers: List[int] = field(default_factory=list)
    ...     def hard_math(self, another_number):
    ...         return self.a_number + sum(self.list_of_numbers) * another_number
    >>> OtherClass=SomeClass
    >>> oc = OtherClass(1, [1, 2, 3])
    >>> oc
    SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
    >>> oc.hard_math(3)
    19