V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
9ohnnyR
V2EX  ›  Python

问下大佬们一个关于**kwargs 的小问题

  •  
  •   9ohnnyR · 2019-09-20 18:52:59 +08:00 · 2284 次点击
    这是一个创建于 1650 天前的主题,其中的信息可能已经有所发展或是发生改变。
    def log(*args, **kwargs):
    print('[Log]', args)
    print('[Log]', *args)
    print('[Log]', kwargs)
    print('[Log]', **kwargs)

    if __name__ == '__main__':
    log(1, 2, host='haha', port=3000)
    ----------------------------------------------------------------------------------------------------------------------
    前三行都是能正常输出的
    输出结果如下:
    [Log] (1, 2)
    [Log] 1 2
    [Log] {'port': 3000, 'host': 'haha'}

    但是第四行会报错

    报错信息如下:
    Traceback (most recent call last):
    File "/Users/liulang/PycharmProjects/class2/server.py", line 31, in <module>
    log(1, 2, host='haha', port=3000)
    File "/Users/liulang/PycharmProjects/class2/server.py", line 28, in log
    print('[Log]', **kwargs)
    TypeError: 'port' is an invalid keyword argument for this function
    7 条回复    2019-09-21 17:30:09 +08:00
    inhzus
        1
    inhzus  
       2019-09-20 18:58:49 +08:00 via Android
    这个问题算是 Python 的基础吧,v 站之前也有过类似问题,Google 关键词 Python dict unpacking and packing。希望可以善用搜索引擎
    9ohnnyR
        2
    9ohnnyR  
    OP
       2019-09-20 19:04:20 +08:00
    @inhzus 好的 谢谢
    ysc3839
        3
    ysc3839  
       2019-09-20 19:13:48 +08:00 via Android
    因为 print 不接受 keyword args。
    ysc3839
        4
    ysc3839  
       2019-09-20 19:15:47 +08:00 via Android
    @ysc3839 更正一下:不是不接受 keyword args,是不接受 port 这个 keyword。
    https://docs.python.org/3/library/functions.html#print
    hushao
        5
    hushao  
       2019-09-20 19:16:05 +08:00
    理解**kwargs 在做什么就知道了
    littlespider89
        6
    littlespider89  
       2019-09-20 19:18:31 +08:00
    第四行相当于 print('[LOG]', port=3000, host='haha')
    你看看 print 的函数签名,就知道了
    oahebky
        7
    oahebky  
       2019-09-21 17:30:09 +08:00
    t = ("foo", "bar")
    print("*args: ", *t)
    相当于 print("*args: ", "foo", "bar")

    kw = {"foo": "bar"}
    print("**kw: ", **kw)
    相当于 print("**kw: ", foo="bar")
    也就是说 **kw 作为参数:
    1. 并非是:func("key1=value1", "key2=value2")
    2. 并非是:func(key1, value1, key2, value2)

    这也是合理,因为它本来就应该是这样子。

    ------

    所以有些代码可能这么写:
    dict_ = {
    "key1": "value1",
    "key2": "value2",
    }

    class A:
    def __init__(key1, key2):
    ...略...

    a = A(**dict_)

    ======
    (因为 V2EX 评论显示问题,所以上面代码的空格无法显示。)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3747 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 10:37 · PVG 18:37 · LAX 03:37 · JFK 06:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.