-1

I looked into the example here C-like structures in Python

But The example is of "bunch" but anyways the code is here

class Bunch:
def __init__(self,  **kwds):
    self.__dict__.update(kwds)

BUt I am using it like this

p = Bunch(x,y)

BUt I am getting a type error

TypeError: __init__() takes exactly 1 argument (3 given)

What am I doing wrong??

Community
  • 1
  • 1
frazman
  • 32,081
  • 75
  • 184
  • 269
  • ooh never mind.. i forgot to pu tthe value. with the filed – frazman Feb 29 '12 at 21:48
  • 1
    You defined `__init__` to not take any positional arguments (apart from `self`), only keyword arguments. But when you instantiate it, you pass two positional arguments. – Felix Kling Feb 29 '12 at 21:48

2 Answers2

3

You have to pass keyword arguments. Otherwise it doesn't know the names you want to give to the attributes x and y.

Try

p = Bunch(x=x, y=y)

To amplify on this, when you see **argname in the arguments to a function or method, it has a very specific meaning. It means take all keyword arguments passed to the function that aren't already named and combine them together into a dict called argname. See below for an example.

>>> class Bunch(object):
...     def __init__(self, **kwargs):
...         self.__dict__.update(kwargs)
...         print kwargs
... 
>>> x, y = 5, 6
>>> p = Bunch(x=x, y=y)
{'y': 6, 'x': 5}
>>> p.x
5
>>> p.y
6

If you try to pass non-keyword args to a function that only accepts **kwargs, you'll get an error.

senderle
  • 145,869
  • 36
  • 209
  • 233
1

You're asking for keyword arguments by using that ** before the **kwds parameter for your __init__ function.

This works:

p = Bunch(x=x, y=y)
Casey Kuball
  • 7,717
  • 5
  • 38
  • 70