1

Hypothetically speaking, assume one has this class:

class Person:
  def __init__(self, lastName, firstName, age,):
    self.lastName = lastName
    self.firstName = firstName
    self.age = age

To add other attributes, it would be the same method. However, writing self.attribute = attribute would become extremely tiresome after a while, especially if a dozen or more attributes were required, in cases of a larger class.

Is there some way to iteratively apply the variable name to the attribute? Perhaps by setting up a loop and applying the attributes autonomously?

Johnny
  • 211
  • 3
  • 15
  • Does this answer your question? [What are data classes and how are they different from common classes?](https://stackoverflow.com/questions/47955263/what-are-data-classes-and-how-are-they-different-from-common-classes) – wwii May 09 '20 at 03:01
  • It's interesting, but not exactly. I'm looking for more of a for loop answer that would be a one or two liner. – Johnny May 09 '20 at 03:28
  • To set up a loop with attribute names you have to type all those attribute names to loop over. Using a dataclass does not involve any more typing than setting up that loop. dataclasses were *made* to lessen the tedium of *making* a class. – wwii May 09 '20 at 03:35
  • Ah, I see. If you drafted a short solution restating what you wrote here I'll mark it off for you. – Johnny May 09 '20 at 03:52

2 Answers2

2

Use the dataclasses module - it reduces the tedium of making a class

>>> from dataclasses import dataclass
>>> @dataclass
... class F:
...     attr1: str
...     attr2: str
...     attr3: str
...     attr4: str
>>> f = F('x','y','z','a')
>>> f
F(attr1='x', attr2='y', attr3='z', attr4='a')
>>> f.attr1
'x'
wwii
  • 23,232
  • 7
  • 37
  • 77
0

You can have arbitrary logic inside the __init__ method, at the end of the day it's function. So there's no problem in something like this

 class myclass:
      def __init__(self,attributes):
         for att in attributes: self.att = att

EDIT: Although this isn't what you are looking for you can try setting the attributes after the init like this

atts = dict(#att:value dictionary)
for att,val in atts: setattr(myclass,att,val)
umbreon29
  • 223
  • 2
  • 8