1

I have written a class, in which the constructor receives a dictionary, as shown in the following code:

class Test:
     def __init__(self, **kwargs):
           for key, value in kwargs.items():
               self.key = value

what i want to do at the end is the ability to reference each key as shown in the following piece of code:

T = Test(age=34, name='david')
print(T.age)

instead i get keyword can't be an expression..

rachid el kedmiri
  • 2,376
  • 2
  • 18
  • 40

2 Answers2

5

You can update the class dict:

class Test:
     def __init__(self, **kwargs):
           self.__dict__.update(kwargs)

You can also query vars and update (one should prefer this to invoking __dunder__ attributes directly).

class Test:
     def __init__(self, **kwargs):
           vars(self).update(kwargs)
cs95
  • 379,657
  • 97
  • 704
  • 746
Netwave
  • 40,134
  • 6
  • 50
  • 93
1

You are setting only the attribute T.key. If you want to dynamically set attributes based on the name of the key, you need setattr:

for key, value in kwargs.items():
    setattr(self, key, value)
Phydeaux
  • 2,795
  • 3
  • 17
  • 35