之前python中有很多参数为*args 和 **kwargs的函数,一直不能理解他们,后来搜索后正确理解:
- 面向对象角度:
One place where the use of*argsand**kwargsis quite useful is for subclassing(子类化).
class Foo(object):
def __init__(self, value1, value2):
# do something with the values
print value1, value2
class 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}
本文详细解释了Python中*args和**kwargs的作用及其应用场景,包括面向对象编程中子类继承父类时如何使用这两个特性,以及在函数定义中如何灵活运用它们来处理不定数量的参数。
533

被折叠的 条评论
为什么被折叠?



