0

I am trying to assign variables dynamically to a class:

Example:

class P:
    def __init__(self, field):
       for key, value in self.func(field):
           self.key = value

field = {'a' : 1, 'b' : 2}

obj = P(field)
print(obj.a)
print(obj.b)

Here I want to assign attributes dynamically to a object, basically keys of field dict as attribute. but I think it will assign 'key' as attribute to that object. How can we do this?

1
  • What is self.func? Commented Oct 9, 2020 at 13:14

2 Answers 2

2

Use setattr to set attributes dynamically:

class P:
    def __init__(self, field):
       for key, value in field.items():  # <== note "items" needed here
           setattr(self, key, value)

field = {'a' : 1, 'b' : 2}

obj = P(field)
print(obj.a)  # 1
print(obj.b)  # 2
Sign up to request clarification or add additional context in comments.

3 Comments

You lost the call to self.func (whatever that is).
@chepner Yes, that was somewhat deliberate. From the description it appears that the items are contained directly in field and that self.func is what the OP thought might be necessary to extract them - in fact field.items()
@chepner BTW, my assumption was largely based on the fact that the key names were the same as in field itself. I now see that you've added a good answer allowing for both possible interpretations, so thanks for that.
2

You need to use setattr, so that the value of the variable, not the name, is used as the attribute to set.

for key, value in self.func(field):
    setattr(self, value, key)

Not knowing what self.func is, it's possible you just want to use the dictionary to initialize attributes, in which case you want

for key, value in field.items():
    setattr(self, key, value)

or simply

self.__dict__.update(field)

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.