Python变量作用域方法

2024-09-29 17:45:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这段python代码。我想要一个名为filetext的全局变量。但是,它没有按预期工作,我想在第一个方法中修改filetext变量,然后在第二个方法中使用它

filetext = "x"

def method1():

    filetext = "heyeeh"

def method2():
    print(filetext)

这将产生“x”。怎么会这样,我怎么才能克服呢


Tags: 方法代码defprint全局变量method1method2filetext
1条回答
网友
1楼 · 发布于 2024-09-29 17:45:14

您需要在这里使用^{},否则python将创建一个新的变量副本,其作用域仅限于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

相关问题 更多 >

    热门问题