我刚开始使用python。我遇到了关键字global
以获取全局变量的值。
假设我有以下代码
str="I'm Global"
def func():
'''
str="Gives error" # can't create a local variable with same name as of global variable
'''
global str
print "Global:: " + str
str="I'm Local" # I don't want to override the global value
print "Local:: " + str
'''
print "Want to print Global value but can't because it's got overriden" + str
'''
func()
用其他语言说C ++我们可以选择是否使用(::范围分辨率运算符)进行i / o操作时使用局部变量或全局变量但是我没有找到类似的东西此
所以在python中有任何选项,我可以创建一个局部变量(是和全局变量同名),使用相同的选项,如C ++来解析范围(全局似乎没有帮助解决这个问题)
答案 0 :(得分:4)
你不能做你想做的事,不是那样的。变量要么总是本地的,要么在整个范围内都是全局变量。
您也可以通过globals()
dictionary访问全局名称:
def func():
print "Global:: " + globals()['str']
str = "I'm Local"
print "Local:: " + str
这样做无论如何都是不好的做法。只需使用不冲突的名称。
您也不应该将名称str
用于变量,而是屏蔽built-in type object。