在python中通过函数传递变量的问题

时间:2016-03-09 16:25:34

标签: python function arguments

我很难理解下面代码中的函数 rhs(u,m,r)是如何接收参数 m r 。从代码中可以看出,函数 rhs 在函数 euler_step(u,rhs,dt)中被调用,但是参数 m < / strong>和 r 作为参数传递给函数 euler_step ,也不是全局变量。所以,有人可以向我解释参数 m u 是如何到达函数 rhs

# model parameters:
mpo = 100.   # initial mass of the rocket propellant in kg
ms = 50.     # mass of the rocket shell in kg
g = 9.81     # gravity in m s^{-2}
rho = 1.091  # average air density in kg/m^{3}
rad = 0.5    # radius of the maximum cross sectional area of the rocket in m
A = numpy.pi*(rad**2)# maximum cross sectional area of the rocket in m^{2}
v_e = 325.   # the exhaust speed in m/s
C_D = 0.15   # drag coefficient
rt = 20.0    # propellant burn rate in kg/s
dtp = 5.0    # time interval to empty the propellant in s

### set initial conditions ###
h0 = 0.0 # start at the zero height [m]
v0 = 0.0 # initial speed [m/s]

def rhs(u, m, r):
    """Returns the right-hand side of the phugoid system of equations.

    Parameters
    ----------
    u : array of float
        array containing the solution at time n.
    mp: float
        mass of the propellant at time t
    mp_rate: float
        propellant burn rate

    Returns
    -------
    dudt : array of float
        array containing the RHS given u.
    """
    print("[m,r]",[m,r])
    [h,v] = u.copy()

    return numpy.array( [ v, -g + pow((ms+m),-1)*(r*v_e - 0.5*rho*v*abs(v)*A*C_D) ] )

def euler_step(u, rhs, dt):
    """Returns the solution at the next time-step using Euler's method.

    Parameters
    ----------
    u : array of float
        solution at the previous time-step.
    rhs : function
        function to compute the right hand-side of the system of equation.
    dt : float
        time-increment.

    Returns
    -------
    u_n_plus_1 : array of float
        approximate solution at the next time step.
    """

    return u + dt * rhs(u, m, r)

if __name__ == "__main__":
    T = 17.0                     # final time
    dt = 0.1                     # time increment
    t = numpy.arange(0.0, T, dt) # time discretization
    N = len(t)                   # number of time-steps

    # initialize the array containing the solution for each time-step
    u = numpy.zeros((N, 2))
    u[0] = numpy.array([h0, v0]) # fill 1st element with initial values
    rate = numpy.zeros(N)
    mp = numpy.zeros(N)
    Np = int(((N)/(T))*dtp) # number of time-steps with propellant burn

    rate[0:Np] = rt # propellant burn rate in kg/s
    mp[0:Np] = mpo - rt*t[0:Np]

    # time loop - Euler method
    for n in range(1,N-1):

        r = rate[n]
        m = mp[n]
        print("[R,M]",[r,m])
        u[n+1] = euler_step(u[n], rhs, dt)

提前致谢。

3 个答案:

答案 0 :(得分:4)

mn 全局变量。

这可能令人困惑,因为__main__似乎是一个功能,但事实并非如此。 if __name__ == "__main__" ....正在全局范围内运行。

答案 1 :(得分:3)

他们全局变量。在Python中,ifwhilefor执行而非创建单独的变量范围,因此在第一个变量范围之前,它们仍然在全局/模块范围内分配值调用euler_step

if __name__ == "__main__":  # does not start a new variable scope
    ...

    for n in range(1,N-1):  # does not start one either
        # thus these variables are set in global scope.
        r = rate[n]
        m = mp[n]

        # and euler_step is invoked only here, thus it will see
        # r and m being set.
        u[n+1] = euler_step(u[n], rhs, dt)

另见Short Description of the Scoping Rules?

答案 2 :(得分:1)

var figlet = require('figlet'); function art(dataToArt, callback) { var arry[]; figlet(dataToArt, function(err, data) { if (err) { console.log('Something went wrong...'); console.dir(err); return callback(''); } arry[0] = data; callback(arry); }); figlet(dataToArt, function(err, data) { if (err) { console.log('Something went wrong...'); console.dir(err); return callback(''); } arry[1] = data; callback(arry); }); } art('Hello World', function (data){ console.log(data); }); m在模块级别的脚本底部附近定义:

r

因此they are available to all functions within the module

  

以下是块:模块,函数体和类   定义。范围定义块内名称的可见性。   如果在块中定义了局部变量,则其范围包括该变量   块。如果定义发生在功能块中,则范围会扩展   包含在定义的块中的任何块,除非包含   block为名称引入了不同的绑定...当名称是   在代码块中使用它,使用最近的封闭解析   范围。