简体   繁体   中英

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

I have wrote the following code in 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

In my project there is also integration.py . In this Python file I need the values which z calculates in the function def interpolation for this calculation:

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

As you can see I have already added z to the function def horizontalAcceleration at the place where it should go. To use z there, I tried the following: from derivation import z

But that doesn't work. Because then I get the error: ImportError: cannot import name 'z' from 'derivation'

Have anybody an idea how I can solve this problem? Thanks for helping me.

I think that your misunderstanding is because you think a function is like a script that has been run and modified a.global state. That's not what a function is. A function is a series of actions performed on its inputs (ignoring closures for a minute) which returns some results. You can call it many times, but without calling it, it never executes. Once it stops executing all its variables go out of scope.

You can import and call a function though. So you can change the return type of Interpolation to return everything you need somewhere else. Eg

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

Then somewhere you import that function, call it, get back all the data you need, then pass that to your other 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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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