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?

Nitin Kothari
  • 77
  • 2
  • 8

2 Answers2

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)
chepner
  • 497,756
  • 71
  • 530
  • 681
1

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
alani
  • 12,573
  • 2
  • 13
  • 23
  • You lost the call to `self.func` (whatever that is). – chepner Oct 09 '20 at 13:15
  • 1
    @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()` – alani Oct 09 '20 at 13:17
  • 1
    @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. – alani Oct 09 '20 at 13:24