将变量从一个函数调用到另一个函数

时间:2017-05-10 01:02:47

标签: python

我查找了类似的问题,但我仍然不明白如何从字符串调用值来传播。当我尝试运行传播时,我得到一个没有定义c的错误。我假设delta t和x也是如此,只是错误触发了它遇到的第一个未定义变量。

def string(T, mu, length):

#legnth is just the number of elements in the array that represents the 
#string, the strings length is 1m
delta_x = 1 / length
#c is the speed of the wave in the string
c = (T / mu) ** (0.5)
delta_t = delta_x / c

string_v = np.zeros((3,length))
return(string_v, delta_x, delta_t, c)

我需要做些什么才能在下一个函数中调用变量?

def propagate(A, omega):

t = 0
r = c * delta_t / delta_x
string_v[0,0] = string_v[1,0] = A*np.sin(omega*t)
while t < 100:

    for i in range(len(length)):
        string_v[2,i] = 2 *(1 - r**2)*string_v[1,i] - string_v[0,i] + r**2(string_v[1,i+1] + string_v[1,i-1])

    for i in range(len(length)):
        string_v[1,i] = string_v[0,i]
        string_v[2,i] = string_v[1,i]

    t = t + delta_t
return(string_v)

2 个答案:

答案 0 :(得分:0)

编辑:您可以使用某种功能重载。这个答案的例子比我的好:Overloaded functions in python?

class不是必需的,也不合适:

  

类的目的是捆绑表示的数据结构   一些逻辑实体,其中包含处理此数据的操作   结构

参考:[Tutor] When to use a Class or just define functions?

您不使用对象或具有属性或数据结构的任何实体。至于我可以说,你正在对“数据”进行计算。只需在需要时使用参数:

def string(T, mu, length):

    #legnth is just the number of elements in the array that represents the 
    #string, the strings length is 1m
    delta_x = 1 / length
    #c is the speed of the wave in the string
    c = (T / mu) ** (0.5)
    delta_t = delta_x / c

    prop_1 = propagate(A=5, omega=6)
    prop_2 = propagate(A=7, omega=8, c=9, delta_t=10, delta_x=11)

    return prop_1, prop_2

def propagate(A, omega, c=None, delta_t=None, delta_x=None):

    # check is any of these variables are not passed into this function
    if not all([c, delta_t, delta_x]):
        answer_a = 'c, delta_t and delta_x not used'
    # otherwise, all variables were passed in
    else:
        answer_a = 'all variables used'

    return answer_a

print string(T=1.1, mu=1.1, length=1)

输出:

('c, delta_t and delta_x not used', 'all variables used')

答案 1 :(得分:0)

您可以将变量作为参数从一个函数传递到另一个函数,也可以将所需变量设置为全局。

相关问题