Python小技巧:args 和 kwargs 的乐趣
那么“args”和“kwargs”参数用来做什么呢?
In [2]: def foo(required, *args, **kwargs):
...: print(required)
...: if args:
...: print(args)
...: if kwargs:
...: print(kwargs)
In [3]: foo()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-c19b6d9633cf> in <module>
----> 1 foo()
TypeError: foo() missing 1 required positional argument: 'required'
In [4]: foo('hello')
hello
In [5]: foo('hello', 1, 2, 3)
hello
(1, 2, 3)
In [6]: foo('hello', 1, 2, 3, key1='value', key2=999)
hello
(1, 2, 3)
{'key1': 'value', 'key2': 999}
## 转发可选或者关键字参数
In [8]: def foo(x, *args, **kwargs):
...: kwarg['name'] = 'Alice'
...: new_args = args + ('extra', )
...: bar(x, *new_args, **kwargs)
In [9]: class Car:
...: def __init__(self, color, mileage):
...: self.color = color
...: self.mileage = mileage
...:
In [10]: class AlwaysBlueCar(Car):
...: def __init__(self, *args, **kwargs):
...: super().__init__(*args, **kwargs)
...: self.color = 'blue'
In [12]: AlwaysBlueCar('green', 48392).color
Out[12]: 'blue'
import functools
def trace(f):
...: @functools.wraps(f)
...: def decorated_function(*args, **kwargs):
...: print(f, args, kwargs)
...: result = f(*args, **kwargs)
...: print(result)
...: return decorated_function
In [11]: @trace
...: def greet(greeting, name):
...: return '{}, {}!'.format(greeting, name)
In [14]: greet('Hello', 'Bob')
<function greet at 0x7fefa69db700> ('Hello', 'Bob') {}
Hello, Bob!
微信扫码关注该文公众号作者
戳这里提交新闻线索和高质量文章给我们。
来源: qq
点击查看作者最近其他文章