0

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().

Aurelie Navir
  • 938
  • 2
  • 7
  • 17
  • 1
    Yes that can be done using some tricks, but that's not recommended better write clean code. And if your requirement is, initialising these same variables inside multiple classes, then definitely you can use inheritance , using `super` keyword. – Sandeep Rawat Jul 19 '22 at 08:39
  • Oh ok, I thought that there was a common method that I didn't know of. Maybe the recommendation is to not extend too much with a high quantity of initialization variables? – Aurelie Navir Jul 19 '22 at 09:05
  • 1
    In such case you can use python's `dataclass` decorator (works with python3.7 or above) as suggested by @Tom McLean – Sandeep Rawat Jul 19 '22 at 09:24

1 Answers1

5

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
Tom McLean
  • 5,583
  • 1
  • 11
  • 36