0

In init method in a class I want to read keys as self.key from a dict kwarg and assign values to them. Look at code to understand.

class Abc:
    def __init__(self,**kwarg):
        for key,value in kwarg.items():
            self.key = value
obj = class(name = 'josh', age = 23, country = 'UK')
print(dir(obj))

obj has only key attribute. I get it why it has key. But I don't know how to read keys to self.key? I think you can get the question. What I except is obj must have name, age, country attributes

KRISHNA I
  • 57
  • 2
  • 11

1 Answers1

0

What you need is setattr:

class Abc:
    def __init__(self, **kwarg):
        for key, value in kwarg.items():
            setattr(self, key, value)
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103