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

2016-04-29 10:48:33 +08:00
 yanyuechuixue

def test(**kwargs):
	for key,value in kwargs.items():
    	locals()['%s' % key] =value
    print ohahahaha
    
    
test(ohahahaha=1)
#NameError: name 'ohahahaha' is not defined

1672 次点击
所在节点    问与答
13 条回复
SErHo
2016-04-29 11:53:03 +08:00
print ohahahaha 的时候,默认 ohahahaha 是全局变量(因为 ohahahaha 并没在函数内赋值过),然后去全局作用域查找的。
mornlight
2016-04-29 12:10:05 +08:00
def 里面是一个新的作用域, print ohahahaha 的时候它在自己作用域和全局作用域里都找不到 ohahahaha ,当然不行。

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

改成
ohahahaha = 1
test(ohahahaha=ohahahaha)
这个就可以跑通了
mornlight
2016-04-29 12:11:41 +08:00
@mornlight 这样用 locals() 也是不行的,强行塞进去太粗暴了
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
2016-04-29 12:16:15 +08:00
print kwargs.get('ohahahaha', '')
yanyuechuixue
2016-04-29 12:23:49 +08:00
@mornlight 原来是这样,谢谢!
sujin190
2016-04-29 13:10:18 +08:00
python 的名称空间分明是编译时就确认的吧,这样改显然是没效果的,属性才是可以动态添加的
111111111111
2016-04-29 14:11:21 +08:00
@mornlight
ohahahaha = 1
test(ohahahaha=ohahahaha)

这样搞 print 出来的是全局变量吧?
楼主说的不是在函数的创建局部变量?
yanyuechuixue
2016-04-29 21:23:28 +08:00
@sujin190 不是哟, python 是解释型语言,而且支持这种操作。
yanyuechuixue
2016-04-29 21:24:11 +08:00
@111111111111 嗯,我是想在局部创建变量,实际上我就是因为参数太多,会乱,所以想让它传进去的时候就有个名字。
sujin190
2016-04-29 21:33:25 +08:00
@yanyuechuixue 其实是不支持的,你可以看下编译出的字节码就知道了,编译时确定了名称空间
yanyuechuixue
2016-04-30 17:49:34 +08:00
@sujin190 Python 为什么要编译呢?
julyclyde
2016-05-04 15:57:16 +08:00
@yanyuechuixue 不是为什么要的问题,而是它就是编译了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/275269

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX