Python小技巧:args 和 kwargs 的乐趣
那么“args”和“kwargs”参数用来做什么呢?
In [
2]:
deffoo(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]:
deffoo(x, *args, **kwargs): ...: kwarg[
'name'] =
'Alice' ...: new_args = args + (
'extra', )
...: bar(x, *new_args, **kwargs)
In [
9]:
classCar: ...:
def__init__(self, color, mileage): ...: self.color = color
...: self.mileage = mileage
...:
In [
10]:
classAlwaysBlueCar(Car): ...:
def__init__(self, *args, **kwargs): ...: super().__init__(*args, **kwargs)
...: self.color =
'blue'In [
12]: AlwaysBlueCar(
'green',
48392).color
Out[
12]:
'blue' functools
deftrace(f):
...: @functools.wraps(f)
...:
defdecorated_function(*args, **kwargs): ...: print(f, args, kwargs)
...: result = f(*args, **kwargs)
...: print(result)
...:
return decorated_function
In [
11]: @trace
...:
defgreet(greeting, name): ...:
return'{}, {}!'.format(greeting, name)
In [
14]: greet(
'Hello',
'Bob')
<function greet at
0x7fefa69db700> (
'Hello',
'Bob') {}
Hello, Bob!
阅读原文
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。