Home > Software design >  passing all init variables to self
passing all init variables to self

Time:07-20

Is there a standard way to pass all arguments defined in __init__() to the whole class (as self arguments)?

For example in my program I usually do it like this:

class DummyClass():
   def __init__(self,x,y,z):
      self.x = x
      self.y = y
      self.z = z
      ...

Is there a way to do the same without individually passing each argument? I think I saw once a similar thing with super().

CodePudding user response:

As per this answer you can do this:

class X(object):
    def __init__(self, x, y, z):
        vars = locals() # dict of local names
        self.__dict__.update(vars) # __dict__ holds and object's attributes
        del self.__dict__["self"] # don't need `self`

A more pythonic answer is to use a dataclass

@dataclass
class X:
    x: float
    y: float
    z: float
  • Related