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,146
  • 2
  • 17
  • 36

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
  • 330,695
  • 80
  • 606
  • 657
Netwave
  • 36,219
  • 6
  • 36
  • 71
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
  • 15
  • 35