1

I have a simple class (Python 3.6):

class MyClass:
    id: int
    a: int
    b: int
    c: int

I wish to set the class attributes when instantiating using a loop, something like:

class MyClass:
    def __init__(self, id):
        self.id = id
        for attr in ['a', 'b', 'c']:
            # put something in "self.attr", e.g. something like: self.attr = 1
    id: int
    a: int
    b: int
    c: int

Why would I want to do this?

  1. the list is long

  2. I'm instantiating some of the values using an external nested dictionary d which has id as keys and a {'a': 1, 'b': 2, 'c': 3} as value

So really this would look like:

class MyClass:
    def __init__(self, id, d):
        self.id = id
        for attr in ['a', 'b', 'c']:
            # put d[id][attr] in "self.attr", e.g. something like: self.attr = d[id][attr]
    id: int
    a: int
    b: int
    c: int

Adding class attributes using a for loop in Python is a similar question, but not identical; I'm specifically interested in looping over attributes when instantiating the class, i.e. in the __init()__ constructor.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Giora Simchoni
  • 3,487
  • 3
  • 34
  • 72

2 Answers2

1

You could put the attributes that you want to set in a class variable and then loop through them with setattr:

class Potato:

    _attributes = ['a', 'b', 'c']

    def __init__(self, id, d):
        for attribute in _attributes:
            setattr(self, attribute, d[id][attribute])
gmds
  • 19,325
  • 4
  • 32
  • 58
0

you can do it using setattr on self:

class MyClass:
    def __init__(self, id, d):
        self.id = id
        for attr in ['a', 'b', 'c']:
            setattr(self, attr, d[id][attr])


d = {"123": {'a': 1, 'b': 2, 'c': 3}}
instance = MyClass("123", d)

print(instance.a)
print(instance.b)
print(instance.c)
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38