Python tips: 什么是*args和**kwargs?

本文介绍了Python中*args和**kwargs的用法,详细解释了它们如何收集多个位置参数和关键字参数,并给出了实例演示。

https://www.cnblogs.com/fengmk2/archive/2008/04/21/1163766.html

Python tips: 什么是*args和**kwargs?

先来看个例子:

def foo(*args, **kwargs):
    print 'args = ', args
    print 'kwargs = ', kwargs
    print '---------------------------------------'

if __name__ == '__main__':
    foo(1,2,3,4)
    foo(a=1,b=2,c=3)
    foo(1,2,3,4, a=1,b=2,c=3)
    foo('a', 1, None, a=1, b='2', c=3)
输出结果如下:

args =  (1, 2, 3, 4)
kwargs =  {}
---------------------------------------
args =  ()
kwargs =  {'a': 1, 'c': 3, 'b': 2}
---------------------------------------
args =  (1, 2, 3, 4)
kwargs =  {'a': 1, 'c': 3, 'b': 2}
---------------------------------------
args =  ('a', 1, None)
kwargs =  {'a': 1, 'c': 3, 'b': '2'}
---------------------------------------

可以看到,这两个是python中的可变参数。*args表示任何多个无名参数,它是一个tuple;**kwargs表示关键字参数,它是一个dict。并且同时使用*args和**kwargs时,必须*args参数列要在**kwargs前,像foo(a=1, b='2', c=3, a', 1, None, )这样调用的话,会提示语法错误“SyntaxError: non-keyword arg after keyword arg”。

 

呵呵,知道*args和**kwargs是什么了吧。还有一个很漂亮的用法,就是创建字典:

    def kw_dict(**kwargs):
        return kwargs
    print kw_dict(a=1,b=2,c=3) == {'a':1, 'b':2, 'c':3}

其实python中就带有dict类,使用dict(a=1,b=2,c=3)即可创建一个字典了。

 

“人生苦短,我用python。”

Technorati 标签: python, tuple, dict, *args, **kwargs


Exception in thread Thread-1: Traceback (most recent call last): File "D:\python377\lib\threading.py", line 926, in _bootstrap_inner self.run() File "D:\python377\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\python377\lib\multiprocessing\pool.py", line 412, in _handle_workers pool._maintain_pool() File "D:\python377\lib\multiprocessing\pool.py", line 248, in _maintain_pool self._repopulate_pool() File "D:\python377\lib\multiprocessing\pool.py", line 241, in _repopulate_pool w.start() File "D:\python377\lib\multiprocessing\process.py", line 112, in start self._popen = self._Popen(self) File "D:\python377\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "D:\python377\lib\multiprocessing\popen_spawn_win32.py", line 72, in __init__ None, None, False, 0, env, None, None) OSError: [WinError 1455] 页面文件太小,无法完成操作。 Traceback (most recent call last): File "<string>", line 1, in <module> File "D:\python377\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "D:\python377\lib\multiprocessing\spawn.py", line 114, in _main prepare(preparation_data) File "D:\python377\lib\multiprocessing\spawn.py", line 225, in prepare _fixup_main_from_path(data['init_main_from_path']) File "D:\python377\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path run_name="__mp_main__") File "D:\python377\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "D:\python377\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "D:\python377\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "D:\code\nba_random_forest_model.py", line 1, in <module> import pandas as pd File "D:\python377\lib\site-packages\pandas\__init__.py", line 17, in <module> "Unable to import required dependencies:\n" + "\n".join(missing_dependencies) ImportError: Unable to import required dependencies: numpy: IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. We have compiled some common reasons and troubleshooting tips at: https://numpy.org/devdocs/user/troubleshooting-importerror.html Please note and check the following: * The Python version is: Python3.7 from "D:\python377\python.exe" * The NumPy version is: "1.19.5" and make sure that they are the versions you expect. Please carefully study the documentation linked above for further help. Original error was: DLL load failed: 出现了内部错误。 D:\python377\lib\site-packages\sklearn\ensemble\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d D:\python377\lib\site-packages\sklearn\ensemble\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d D:\python377\lib\site-packages\sklearn\ensemble\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d D:\python377\lib\site-packages\sklearn\ensemble\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d D:\python377\lib\site-packages\sklearn\ensemble\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d D:\python377\lib\site-packages\sklearn\ensemble\weight_boosting.py:29: DeprecationWarning: numpy.core.umath_tests is an internal NumPy module and should not be imported. It will be removed in a future NumPy release. from numpy.core.umath_tests import inner1d 在机器学习的过程中出现这样的问题是怎么回事
最新发布
09-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值