简体   繁体   中英

Calling a function from inside a function

from numpy import *
from matplotlib.pyplot import *



c = 299792458 # m/s 
lamda = 643.5 *10**-9 # m

def read_file(filename):
    text_array = loadtxt(filename)
    time = text_array[:, 0]
    obs_lambda = text_array[:, 1]
    flux = text_array[:, 2]
    return [flux,time,obs_lambda]


def rad_vel(data):
    v_r = zeros(len(data[2]))
    for i in range(len(data[2])):
        v_r = c*(((data[2][i] - lamda))/(lamda))
    print v_r
    plot(data[1],v_r)
    show()
    return v_r

    test1 = read_file("test.txt")
    print test1

When I called the function it was a difference in dimensions with v_r and time. len(time) or len(data[2]) was an array with 5087 elements, but v_r was a scalar . Can't really understand how v_r is a scalar ?

I can't try this without the file or modules, but here's one that uses a class.

from numpy import *
from matplotlib.pyplot import *
def readFileData(filename): # Reads file
    text_array = loadtxt(filename)
    ...
    flux = ... # array read from .txt
    time = ... # array read from .txt
    obs_lambda = ... # array read from .txt
    return [flux,time,obs_lambda]

def rad_vel(data): # Finds radial velocity
    for i in range(len(data[2])):
        v_r = data[2][i] - 2
    plot(data[1],v_r)
    show()
    return v_r
textData=readFileData("test.txt")
print(rad_vel(textData))

If I understand correctly, here maybe what you want. I guess you want a helper function

def read_file(filename): # Reads file
    def rad_vel(flux,time,obs_lambda): # Finds radial velocity

        # should you declare v_r in here? 
        v_r = 0  

        for i in range(len(obs_lambda)):
            v_r = obs_lambda[i] - 2
        plot(time,v_r)
        show()
        return v_r

    text_array = loadtxt(filename)
    ...
    flux = ... # array read from .txt
    time = ... # array read from .txt
    obs_lambda = ... # array read from .txt
    return rad_vel(flux,time,obs_lambda)

Along with other values you have to return the inside function too like

return [rad_vel,flux,time,obs_lambda]

test1 = read_file("test.txt")

test1[0]('test.txt')

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