Python小技巧:args 和 kwargs 的乐趣
Python与算法社区
共 2900字,需浏览 6分钟
·
2022-05-20 21:57
那么“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)-3 -c19b6d9633cf> in
----> 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') 0x7fefa69db700 > ('Hello', 'Bob') {}
Hello, Bob!
评论