Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubts in Python code

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:

  • What is the meaning of the * and the ** in the parameters "args" and "kwds"?
  • What is the meaning of "super"?
  • In this classe we are extending the "dict" class? This is a built-in class?

Best Regards,

like image 831
André Avatar asked Apr 22 '26 09:04

André


1 Answers

*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.

like image 177
Aaron Digulla Avatar answered Apr 24 '26 00:04

Aaron Digulla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!