示例代码从一个模块:如何在Python中使用具有相同名称的命名参数和全局变量?
somevar = "a"
def myfunc(somevar = None):
# need to access both somevars ???
# ... if somevar was specified print it or use the global value
pass
if __name__ == '__main__':
somevar = "b" # this is just for fun here
myfunc("c")
myfunc() # should print "a" (the value of global variable)
至少有两个原因使用相同的名称:教育(学习如何使用本地/全局)和使用在模块。
让我们说这个代码是你的模块的一部分:mymodule
和你想要做的事情,如:
import mymodule
mymodule.samevar = "default"
...
mymodule.myfunc(somevar = "a")
...
mymodule.myfunc()
正如你在这个例子被简化想象,想象somevar
参数是许多可选的一个参数,并且myfunc在许多地方被调用。
您是否尝试过关键词'global'和'local'? – NickHalden 2010-08-10 17:13:15
第二个电话应该真的打印“C”,还是应该是“a”? – theomega 2010-08-10 17:19:20
@theomega:谢谢你的评论,我纠正了这个例子。 – bogdan 2010-08-11 09:33:46