繁体   English   中英

如何在另一个 Python 文件中使用另一个 function 中的 function 的计算值?

[英]How can I use a calculated value of a function in another function in another Python file?

我在derivation.py中编写了以下代码:

def Interpolation(ableitungWinkel,x_values):
    
    z = medfilt(derivation,3)
    diff = abs(derivation-z) 
    new_smootheddata = np.where(diff>3,z,derivation)
    x=np.arange(0,len(x_values[:-2]))    
    f = interp1d(x,new_smootheddata,kind="linear")   
    xnew = np.arange(0, len(x_values[:-3]),0.01)
    ynew = f(xnew)
    s=plt.plot(x, z,"o",xnew, ynew, "-")
    
    return s

在我的项目中还有integration.py 在这个 Python 文件中,我需要z在 function def interpolation中计算的值用于此计算:

def horizontalAcceleration(strideData):
    resultsHorizontal = list()

    for i in range (len(strideData)):
        yAngle = z
        xAcceleration = strideData.to_numpy()[i, 4]
        yAcceleration = strideData.to_numpy()[i, 5]
        
        a = ((m.cos(m.radians(yAngle)))*yAcceleration)-((m.sin(m.radians(yAngle)))*xAcceleration) 

        resultsHorizontal.append(a)

    resultsHorizontal.insert(0, 0)
    
    return resultsHorizontal

如您所见,我已经在 go 的位置将 z 添加到 function def HorizontalAcceleration 中。 要在那里使用 z,我尝试了以下方法: from derivation import z

但这不起作用。 因为那时我得到了错误: ImportError: cannot import name 'z' from 'derivation'

有人知道我该如何解决这个问题吗? 谢谢你帮助我。

我认为您的误解是因为您认为 function 就像一个脚本,已经运行并修改了 a.global state。 这不是 function 是什么。 function 是对其输入执行的一系列操作(忽略一分钟的闭包),返回一些结果。 您可以多次调用它,但不调用它,它永远不会执行。 一旦它停止执行 scope 之外的所有变量 go。

不过,您可以导入并调用 function。 因此,您可以更改 Interpolation 的返回类型以在其他地方返回您需要的所有内容。 例如

def Interpolation(...):
...
return {'z': z, 's': s}

然后在某个地方导入 function,调用它,取回您需要的所有数据,然后将其传递给您的其他 function。

import Interpolation from derivation
# get z and s in a dict result
result = Interpolation(...)
# pass s as well as the other argument to your other function
horizontalAcceleration(strideData, result['s'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM