开发者

Doubts in Python code

I'm reading a book of 开发者_StackOverflow社区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,


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


  1. http://docs.python.org/reference/compound_stmts.html#function-definitions. Explains * and **.

  2. http://docs.python.org/library/functions.html?highlight=super#super. Explains super

  3. http://docs.python.org/library/stdtypes.html#mapping-types-dict. Explains dict.


In this classe we are extending the "dict" class? This is a built-in class?

You are actually extending the base dict class. This is a native class in Python. In previous versions of Python you could not extend native classes, but that has changed with new-style classes.

What is the meaning of "super"?

The function super lets you find the parents of a given class, using the same order it would be used for inheritance.

What is the meaning of the * and the ** in the parameters "args" and "kwds"?

*args is expanded with a tuple containint the non-named arguments, while **kwargs is expanded to a dictionary containing the named arguments. It is a way to manage functions with a variable number of arguments.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜