理解python中的 *args??? and **kwargs???

来源:互联网 发布:金蝶软件最新版本 编辑:程序博客网 时间:2024/05/16 08:35

之前python中有很多参数为*args 和 **kwargs的函数,一直不能理解他们,后来搜索后正确理解:

  • 面向对象角度:
    One place where the use of *args and **kwargs is quite useful is for subclassing(子类化).
class Foo(object):    def __init__(self, value1, value2):        # do something with the values        print value1, value2class MyFoo(Foo):    def __init__(self, *args, **kwargs):        # do something else, don't care about the args        print 'myfoo'        super(MyFoo, self).__init__(*args, **kwargs)

This way you can extend the behaviour of the Foo class, without having to know too much about Foo. This can be quite convenient if you are programming to an API which might change. MyFoo just passes all arguments to the Foo class.

  • 函数角度:
    Here’s an example that uses 3 different types of parameters.
def func(required_arg, *args, **kwargs):    # required_arg is a positional-only parameter.    print required_arg    # args is a tuple of positional arguments,    # because the parameter name has * prepended.    if args: # If args is not empty.        print args    # kwargs is a dictionary of keyword arguments,    # because the parameter name has ** prepended.    if kwargs: # If kwargs is not empty.        print kwargs>>> func()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: func() takes at least 1 argument (0 given)>>> func("required argument")required argument>>> func("required argument", 1, 2, '3')required argument(1, 2, '3')>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")required argument(1, 2, '3'){'keyword2': 'foo', 'keyword1': 4}
0 0
原创粉丝点击