我先发布我的代码,然后提问.
def menu(**arg):
if len(arg) == 0:
name = raw_input("Enter your name: ")
location = raw_input("Enter your name: ")
else:
for i,j in arg.items():
globals()[i] = j
print "Name: %s | Location: %s" % (name, location)
Run Code Online (Sandbox Code Playgroud)
这个函数的目标是打印出这样的东西:
姓名:某人| 位置:某个地方
如果我只是输入
菜单()
好的,没问题,但如果我输入
menu(name ='someone',location ='somewhere')
有些不对劲...
如果我像这样重写它:
def menu(**arg):
if len(arg) == 0:
pass
else:
for i,j in arg.items():
globals()[i] = j
print "Name: %s | Location: %s" % (name, location)
Run Code Online (Sandbox Code Playgroud)
我打字
menu(name ='someone',location ='somewhere')
它有效...但我不知道为什么
另外,为什么我不能用"重写版本"中的globals()替换vars()?
我的最后一个问题是......
我发现这段代码冗长冗余..
有没有什么方法可以让它更干净整洁?
谢谢你的耐心!
sen*_*rle 11
首先,不要修改globals- 这是不必要的,过于复杂.如果len(args) == 0,只需创建一个args带有a name和location值的字典.
与代码中的实际问题,但问题在于,一旦你定义location和name 任何地方的功能-即使是在一个if条款- Python的期望location和name将是局部变量.那么当你引用location并且name,Python在本地命名空间中查找它们时,找不到它们,并抛出一个UnboundLocalError.
>>> x = 1
>>> def foo():
... if False:
... x = 2
... print x
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in foo
UnboundLocalError: local variable 'x' referenced before assignment
Run Code Online (Sandbox Code Playgroud)