【Python】Python小技巧:args 和 kwargs 的乐趣
机器学习初学者
共 3018字,需浏览 7分钟
·
2022-05-27 21:24
那么“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!
往期精彩回顾
适合初学者入门人工智能的路线及资料下载 (图文+视频)机器学习入门系列下载 中国大学慕课《机器学习》(黄海广主讲) 机器学习及深度学习笔记等资料打印 《统计学习方法》的代码复现专辑 机器学习交流qq群955171419,加入微信群请扫码:
评论