1

say you have a class that looks like this

class class_name():
    def __init__(self,var1, var2, var3, var4, var5):
        self.var1 = var1
        self.var2 = var2
        self.var3 = var3
        self.var4 = var4
        self.var5 = var5

this can get very long. I have already tried to use a for loop and an exec statement but that did not work. is there a shorter way to assign all of the variables to the class?

3
  • 6
    dataclasses.dataclass docs.python.org/3/library/dataclasses.html Commented Nov 19, 2020 at 19:31
  • 1
    You could potentially have the constructor take a list or dict instead of a bunch of individual values. Depends a lot on the context, but when I have a big set of related values I'll usually define them as a NamedTuple and pass them around that way. Commented Nov 19, 2020 at 19:34
  • 1
    At the point that the list of variables is getting log, one usually switches to using a data structure...a list or a dictionary. (or a NamedTuple, as @Samwise suggests) Commented Nov 19, 2020 at 19:34

3 Answers 3

3

That looks like a dataclass.

Assuming your vars are strings you can define a dataclass like this:

from dataclasses import dataclass

@dataclass
class ClassName:
    var1: str
    var2: str
    var3: str
    var4: str
    var5: str

This automatically defines an init method like this:

def __init__(self, var1: str, var2: str, var3: str, var4: str, var5: str):
    self.var1 = var1
    self.var2 = var2
    self.var3 = var3
    self.var4 = var4
    self.var5 = var5

https://docs.python.org/3/library/dataclasses.html

Sign up to request clarification or add additional context in comments.

1 Comment

better answer is not accepted answer. hmmm
0

You could do something like this... Although this is pretty magic and not recommended.

class ClassName:
   def __init__(self, **kwargs):
      for key, value in kwargs.items():
         setattr(self, key, value)

Used like

my_class = ClassName(first=1, second=2, third=3)

print(my_class.first)  # 1
print(my_class.second)  # 2
print(my_class.third)  # 3

This requires you to provide all arguments as keyword arguments (e.g. key=value. This will error if you try to create the class with just values and no keys.

# This does not work
my_class = ClassName(1, 2, 3)

Again I have to reiterate that this is not recommended. Letting users of your class know exactly what variables they should be passing in to construct your class is extremely valuable.

1 Comment

This is what I also was thinking, but it would require you to do myVar = ClassName(var1='a', var2='b'). You'd have add the parameter names when creating a new object.
0

Use *args-style argument packing.

class class_name():
    def __init__(self, *vars):
        self.vars = vars
        # now you can access self.vars[0], self.vars[1], etc.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.