V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yanyuechuixue
V2EX  ›  问与答

这样通过 kwargs 的方式传递参数,然后动态定义变量为什么是不对的?

  •  
  •   yanyuechuixue · 2016-04-29 10:48:33 +08:00 · 1665 次点击
    这是一个创建于 2911 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    def test(**kwargs):
    	for key,value in kwargs.items():
        	locals()['%s' % key] =value
        print ohahahaha
        
        
    test(ohahahaha=1)
    #NameError: name 'ohahahaha' is not defined
    
    
    13 条回复    2016-05-04 15:57:16 +08:00
    SErHo
        1
    SErHo  
       2016-04-29 11:53:03 +08:00
    print ohahahaha 的时候,默认 ohahahaha 是全局变量(因为 ohahahaha 并没在函数内赋值过),然后去全局作用域查找的。
    mornlight
        2
    mornlight  
       2016-04-29 12:10:05 +08:00
    def 里面是一个新的作用域, print ohahahaha 的时候它在自己作用域和全局作用域里都找不到 ohahahaha ,当然不行。

    test(ohahahaha=1) 这句只是传了一个 key 为 ohahahaha 的参数进去,并没有定义出一个新的变量。

    改成
    ohahahaha = 1
    test(ohahahaha=ohahahaha)
    这个就可以跑通了
    mornlight
        3
    mornlight  
       2016-04-29 12:11:41 +08:00
    @mornlight 这样用 locals() 也是不行的,强行塞进去太粗暴了
    mornlight
        4
    mornlight  
       2016-04-29 12:12:40 +08:00
    locals()
    Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

    Note The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
    tonghuashuai
        5
    tonghuashuai  
       2016-04-29 12:16:15 +08:00
    print kwargs.get('ohahahaha', '')
    yanyuechuixue
        6
    yanyuechuixue  
    OP
       2016-04-29 12:23:49 +08:00
    @mornlight 原来是这样,谢谢!
    sujin190
        7
    sujin190  
       2016-04-29 13:10:18 +08:00
    python 的名称空间分明是编译时就确认的吧,这样改显然是没效果的,属性才是可以动态添加的
    111111111111
        8
    111111111111  
       2016-04-29 14:11:21 +08:00
    @mornlight
    ohahahaha = 1
    test(ohahahaha=ohahahaha)

    这样搞 print 出来的是全局变量吧?
    楼主说的不是在函数的创建局部变量?
    yanyuechuixue
        9
    yanyuechuixue  
    OP
       2016-04-29 21:23:28 +08:00
    @sujin190 不是哟, python 是解释型语言,而且支持这种操作。
    yanyuechuixue
        10
    yanyuechuixue  
    OP
       2016-04-29 21:24:11 +08:00
    @111111111111 嗯,我是想在局部创建变量,实际上我就是因为参数太多,会乱,所以想让它传进去的时候就有个名字。
    sujin190
        11
    sujin190  
       2016-04-29 21:33:25 +08:00
    @yanyuechuixue 其实是不支持的,你可以看下编译出的字节码就知道了,编译时确定了名称空间
    yanyuechuixue
        12
    yanyuechuixue  
    OP
       2016-04-30 17:49:34 +08:00
    @sujin190 Python 为什么要编译呢?
    julyclyde
        13
    julyclyde  
       2016-05-04 15:57:16 +08:00
    @yanyuechuixue 不是为什么要的问题,而是它就是编译了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3351 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 12:07 · PVG 20:07 · LAX 05:07 · JFK 08:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.