Is there any way to simplify the initialization of classes in Python?


I have a class constructor something like this:

class A:
    def __init__(self, a1, a2, ..., an):
        self.a1 = a1
        self.a2 = a2
        ... = an

Is it possible to somehow simplify the initialization process, otherwise writing n repeated lines is not at all interesting.

UPD. I will add to the question:

  1. What if there are default values?
     class B: def __init__(self, b1=b1_0, b2=b2_0, ..., bn=bn_0): self.b1 = b1 self.b2 = b2 ... = bn ...
  2. Perhaps the answer will follow from paragraph 1, but I will still ask one more question: What if for some arguments there is a default value, but for some not?


Then so:

class A:
    def __init__(self, **kwargs):

kwargs is a dictionary of arguments (name: value pairs).

Option with default values:

class A:
     __defaults = dict(b1=1, b2='2', foo='bar')

     def __init__(self, **kwargs):

Initially, the class is initialized with default values ​​( __defaults ), and then with values ​​from kwargs . If kwargs has arguments present in __defaults , then the new values ​​(from kwargs ) will replace the old ones (from __defaults ).

You can use the store_attr function from the fastcore library, it takes all the parameters of the method and writes their values ​​to the attributes of the object with the same names (if some parameter does not need to be written to the attributes, this can be configured, see the documentation).

from fastcore.utils import store_attr

class B:
    def __init__(self, a, b1=1, b2=2, b3=333):
    def update(self, a, b1, b2, b3):

b = B(a='aaa')
print(b.a, b.b1, b.b2, b.b3)

b.update('bbb', 3, 2, 1)
print(b.a, b.b1, b.b2, b.b3)
Scroll to Top