在Python中使用另一个函数的局部变量?
问题描述:
我在一个函数中创建了一个文本文件。对于学校项目,我必须取得该文本文件,并使用相同的数据放入另一个文本文件“distance”,然后将变量“equation”附加到前一个文本文件中每行的末尾。然而,我坚持如何在第一个函数中使用x,y,z变量,并在不使用全局变量的情况下在第二个函数中使用它们?帮帮我!在Python中使用另一个函数的局部变量?
def readast():
astlist=[]
outFileA=open('asteroids.txt','w')
letter=65
size_of_array=15
astlist=[]*size_of_array
for i in range(0,size_of_array):
x=random.randint(1,1000)
y=random.randint(1,1000)
z=random.randint(1,1000)
outFileA.write ('\n'+chr(letter) + '\t' +(str(x)) + '\t' + (str(y)) +'\t' +(str(z)))
letter= letter+ 1
return x,y,z
outFileA.close()
def distance():
outFileA=open('asteroids.txt','r')
outFileD=open('distance.txt','w')
x= (x**2)
y= (y**2) #these three variables I need to pull from readast
z= (z**2)
equation=math.sqrt(x+y+z)
for row in range(len(outfileA)):
x,y,z=outFileA[row]
outFileD.append(equation)
outFileD.close()
答
如果你可以修改函数签名,参数distance
:
def distance(x, y, z):
那么当你从main
调用readast
,抢返回值:
x, y, z = readast()
和通过x
,y
,并且z
当你从main
调用distance
参数:
distance(x, y, z)
注意,有几个地方变量命名x
。您不在多个函数之间共享局部变量;只有它的价值。函数调用将参数的值复制到参数中,然后评估其返回的值。
答
我认为最简单的方法是通过函数参数
def distance(_x, _y, _z):
outFileA=open('asteroids.txt','r')
outFileD=open('distance.txt','w')
x= (_x**2)
y= (_y**2) #these three variables I need to pull from readast
z= (_z**2)
...
,但我认为你需要重新考虑的解决方案,你可以做这样的功能:
def equation(x, y,z):
return math.sqrt(math.pow(x,2)+math.pow(y,2)+math.pow(z,2))
然后调用它当你正确的第一个文件
astlist=[]*size_of_array
for i in range(0,size_of_array):
x=random.randint(1,1000)
y=random.randint(1,1000)
z=random.randint(1,1000)
outFileA.write ('\n'+chr(letter) + '\t' +str(x)+ '\t' +str(y)+'\t' +str(z)+ '\t' +str(equation(x,y,z)))
letter= letter+ 1
outFileA.close()
答
你正在返回(x,y,z)的第一个函数,其中被主函数调用? 确保您的主要功能分配的元组的东西,然后将它作为参数传递到第二函数...
简化:
def distance(x,y,z):
....
def main():
...
(x ,y ,z) = readast()
...
distance(x,y,z)
你不必做你自己'的距离()'计算,只需使用['math.hypot()'](https://docs.python.org/2/library/math.html?highlight=hypot#math.hypot)函数即可。 – martineau 2014-11-22 21:35:44
何时使用“距离”功能?它是从'readast'调用的吗? – sleeparrow 2014-11-22 21:37:46
@Adamantite,主函数中调用'distance'函数,这里没有显示。我的教授说每个函数都应该只做一件事,否则我会把追加函数和'readast'放在同一个函数中。距离函数用于创建一个新的文本文件distance.txt,其值与asteroids.txt相同,然后将更多值附加到distance.txt中(如果有意义的话) – Jackie 2014-11-22 21:40:52