Return语句在Python 3.4.3中不起作用
出于某种原因,Python解释器在被另一个函数访问时不会修改函数中的返回语句值Return语句在Python 3.4.3中不起作用,python,Python,出于某种原因,Python解释器在被另一个函数访问时不会修改函数中的返回语句值 x=10 def example(): global_variable_x = x print(" i know i can access it", global_variable_x) global_variable_x +=5 print(" woa, i can modify it" ,global_variable_x) return global_variable
x=10
def example():
global_variable_x = x
print(" i know i can access it", global_variable_x)
global_variable_x +=5
print(" woa, i can modify it" ,global_variable_x)
return global_variable_x
example()
def modify_another_function():
return 10*example()
modify_another_function()
“内部打印”示例将始终显示相同的内容 这是因为在
示例的上下文中
没有任何变化
差异仅在示例
内部修改另一个功能
外部可见。与10的乘法发生在示例
之外,如果您将修改另一个函数
更改为此,您将看到区别:
def modify_another_function():
return print 10*example()
该程序按预期运行 您定义了
global\u variable\u x=x
并给它起了一个名称global\u variable,但实际上它是一个局部变量。保持数据持久性的最简单方法是修改x
,或者使用类并将其写入类变量
要向您提供更详细的信息,请执行以下操作:
x=10
def example():
global_variable_x = x
print(" i know i can access it", global_variable_x)
global_variable_x +=5
print(" woa, i can modify it" ,global_variable_x)
return global_variable_x
example()
它可能是抽象的,但只是给你一些想法:
- 您将把x=10放在编程堆栈上李>
- 您将调用example()
- example()函数调用将为此创建一个新的堆栈框架
函数调用将
放在上面全局变量\ux
- 当函数调用点击
语句时,堆栈帧将 被移除后,剩下的只有return
x
- 第二次运行
时,它将创建一个新堆栈 框架中,再次将example()
放在它上面,然后再次实例化它 值为全局变量\ux
,为10x
这里的问题与范围界定有关,我建议您看看:我想您的意思是您得到的是:
i know i can access it 10
woa, i can modify it 15
i know i can access it 10
woa, i can modify it 15
我想你想要的是:
i know i can access it 10
woa, i can modify it 15
i know i can access it 15
woa, i can modify it 20
您可以通过以下操作获得:
x=10
def example():
print(" i know i can access it", x)
x +=5
print(" woa, i can modify it", x)
return x
example()
def modify_another_function():
return 10*example()
modify_another_function()
但你不能像现在这样做,因为数字是值,是不可变的。所以,如果你复制它们,你只是复制它们的值,而不是对它们的引用。
print example()
你会看到它确实会返回。在这样一个问题中,有必要解释你期望它返回什么,它会返回什么。当我在使用python 3的example()之前添加print时,它给出了无效的语法,将其更改为print(example())
谢谢您的回复。我之前确实添加了“print”语句,但是python给了我无效的语法!