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?
the list is long
I'm instantiating some of the values using an external nested dictionary
d
which hasid
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.