0
class Obj:
    def __init__(self, **kw):
        # code

obj = Obj(a=5, b=10)
print(obj.a, obj.b) # 5 10

Is there a proven solution to this task?

Redwire
  • 9
  • 1

1 Answers1

2

You can do the following to assign attributes passed in **kw:

class Obj:
    def __init__(self, **kw):
        # in case of python 2, the following line is: for k, v in kw.iteritems():
        for k, v in kw.items():
            setattr(self, k, v)

and then use the way you mentioned in your post:

obj = Obj(a=5, b=10)
print(obj.a, obj.b) # 5 10
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
akazuko
  • 1,394
  • 11
  • 19
  • 1
    @jonas-bystrom your edit is wrong as you can see here ```Python 3.7.3 (default, Dec 13 2019, 19:58:14) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> k = {"a": "b"} >>> k.iter() Traceback (most recent call last): File "", line 1, in AttributeError: 'dict' object has no attribute 'iter' >>> k.items() dict_items([('a', 'b')])``` – akazuko Apr 23 '20 at 07:13
  • @jonas it's called *items* in Python 3, as was already commented in the post – jonrsharpe Apr 23 '20 at 07:14
  • 1
    Syntax error in brain, sorry bout that! `iteritems()` is not present in py3 however so retried my fix with the correct name and reversed the comment as op's question was about py3. – Jonas Byström Apr 23 '20 at 07:28