Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python __init__(self,**kwargs) takes 1 positional argument but 2 were given [duplicate]

I'm creating a simple class in Python 3.6 that should accept keys,values from a dictionary as arguments

my code:

class MyClass:
    def __init__(self, **kwargs):
        for a in kwargs:
            self.a=kwargs[a]
            for b in a:
                self.a.b = kwargs[a][b]
Test = MyClass( {"group1":{"property1":100, "property2":200},\
    "group2":{"property3":100, "property4":200}})

My code returns an error:

TypeError: init() takes 1 positional argument but 2 were given

I expect Test.group2.property4 to return 200

There are many similar questions I found however main problem everywhere is absence of "self" inside init method. But I have it.

Could someone explain the reason for this error? Thanks

like image 738
Dant Avatar asked May 25 '17 14:05

Dant


1 Answers

Pass the parameter(s) as an unpacked dict, not as a single positional argument:

MyClass(**{"group1":{"property1":100, "property2":200},\
    "group2":{"property3":100, "property4":200}})
like image 143
Moses Koledoye Avatar answered Sep 29 '22 03:09

Moses Koledoye