问题描述
我是来自Java的Python新手,想知道如何在Python中将变量从一个函数访问到另一个函数.从此代码:
I'm new to python coming from a Java background and was wondering how to access variables from one function to another in Python. From this code:
def method1():
var1 = randomArray[::2]
var2 = randomArray[1::2]
return var1
return var2
def method2():
for i in range (len(var1)):
print i
我会收到错误消息:
NameError: global name 'var1' is not defined
请原谅代码,我只是提供一个示例.关于如何在方法2中使用var1的任何建议都将大有帮助.谢谢.
Forgive the code, I'm just providing an example. Any advice on how to use var1 in method 2 would be of great help. Thanks.
class Sample:
def method1():
randomArray = [1,2,3,4,5,6,7,8,9,10]
var1 = randomArray[::2]
var2 = randomArray[1::2]
return var1, var2
def method2():
var1, var2 = method1()
for i in range (len(var1)):
print i
在method2()中调用method1()仍然出错.
Still an error with method1() being called in method2().
推荐答案
在Python中,return
语句退出该函数.因此,您的第二个return var2
代码行将永远无法到达.最好的方法是在调用函数时将返回值分配给变量.这是一个示例:
In Python the return
statement exits the function. So your second return var2
line of code will never be reached. The best way to get this done is to assign your return value to a variable when you call the function. Here is an example:
def method1():
var1 = randomArray[::2]
return var1
def method2():
var1 = method1()
for i in range (len(var1)):
print i
您还可以返回多个变量,但是您有打包它们,例如作为 tuple 或列表.
You can also return multiple variables but you have to package them, for example as a tuple or a list.
元组示例:
def method1():
var1 = randomArray[::2]
var2 = randomArray[1::2]
return (var1, var2)
def method2():
var1, var2 = method1()
for i in range (len(var1)):
print i
for i in range (len(var2)):
print i
列表示例:
def method1():
var1 = randomArray[::2]
var2 = randomArray[1::2]
return [var1, var2]
def method2():
varList = method1()
for i in range (len(varList[0])):
print i
for i in range (len(varList[1])):
print i
这是一个基于您更新后的代码的OOP示例:
Here is an OOP example based on your updated code:
class Sample:
def method1(self):
randomArray = [1,2,3,4,5,6,7,8,9,10]
var1 = randomArray[::2]
var2 = randomArray[1::2]
return var1, var2
def method2(self):
var1, var2 = self.method1()
print var1
MySample = Sample()
MySample.method2()
这篇关于在Python中访问其他函数中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!