2024-09-29 17:45:14 发布
网友
我有这段python代码。我想要一个名为filetext的全局变量。但是,它没有按预期工作,我想在第一个方法中修改filetext变量,然后在第二个方法中使用它
filetext = "x" def method1(): filetext = "heyeeh" def method2(): print(filetext)
这将产生“x”。怎么会这样,我怎么才能克服呢
您需要在这里使用^{},否则python将创建一个新的变量副本,其作用域仅限于method1()这里的函数。因此,您的代码应为:
method1()
filetext = "x" def method1(): global filetext # added global here filetext = "heyeeh" def method2(): print filetext
运行示例:
>>> method2() # print original string x >>> method1() # Updates the value of global string >>> method2() # print the updated value of string heyeeh
您需要在这里使用^{} ,否则python将创建一个新的变量副本,其作用域仅限于
method1()
这里的函数。因此,您的代码应为:运行示例:
相关问题 更多 >
编程相关推荐