Search code examples
pythonpython-3.xconstructormethod-parameters

Is there a short way to instantiate a class with the constructor params?


I am using python 3.4

class baba():
  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

IS there a shorter way to write this? Beside getting all of those as a dict


Solution

  • You can use **kwargs, then use setattr to create your instance attributes:

    class baba():
        def __init__(self, **kwargs):
            for i in kwargs:
                setattr(self, i, kwargs[i])
    
    b = baba(a=1,b=2,c=4,d=5)
    print(b.a) # prints 1