2

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.

2

2 Answers 2

2

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])
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.