I'm reading a book of Algorithms in Python, and I'm also new to Python.
I can't understand this example:
class Bunch(dict):
def __init__(self, *args, **kwds):
super(Bunch, self).__init__(*args, **kwds)
self.__dict__ = self
x = Bunch(name="Jayne Cobb", position="Public Relations")
print x.name
Some questions:
Best Regards,
*args means: Collect all extra parameters without a name in this list:
def x(a, *args): pass
x(1, 2, 3)
assigns a=1 and args=[2,3].
**kwargs assigns all extra parameters with a name to the dict kawrgs:
def x(a, **kw): pass
x(1, b=2, c=3)
assigns a=1 and kw={b=2, c=3}.
The code super(Bunch, self).__init__(*args, **kwds) reads: Call the method __init__ of Bunch with the instance self and the parameters *args, **kwds. It's the standard pattern to initialize superclasses (docs for super)
And yes, dict is a built-in data type for dictionaries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With