**kwargs not passing variables to function, what's wrong?
本问题已经有最佳答案,请猛点这里访问。
出于某种原因,我无法让接收函数看到在python中以**kwargs传递的变量。(已解决-请参见编辑)。这说明了问题所在,*kwargs参数通过几个函数传递,并传递给
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | def integrand(x, F, K, T1, T2, vol, flag): print(kwargs) d1 = (np.log(x / (x+K)) + 0.5 * (vol**2) * (T2-T1)) / (vol * np.sqrt(T2 - T1)) d2 = d1 - vol*np.sqrt(T2 - T1) mu = np.log(F) - 0.5 *vol**2 * T1 sigma = vol * np.sqrt(T1) value = lognorm.pdf(x, scale=np.exp(mu), s=sigma) * (flag * x*norm.cdf(flag * d1) - flag * (x+K)*norm.cdf(flag * d2)) return value def integrate(x, w, a, **kwargs): return np.sum(w*transform_integral_negative1_1_to_0_1(x, a, **kwargs)) def transform_integral_0_1_to_Infinity(x, a, **kwargs): return integrand(a+(x/(1-x)), **kwargs) *(1/(1-x)**2); def transform_integral_negative1_1_to_0_1(x, a, **kwargs): return 0.5 * transform_integral_0_1_to_Infinity((x+1)/2, a, **kwargs) flag = current_opt[i,0] F = current_opt[i,1] K = current_opt[i,2] T2 = current_opt[i,3] T1 = current_opt[i,4] r = current_opt[i,5] vol = current_opt[i,6] a = 0 b = np.Inf kwargs = {'flag':flag, 'F':F, 'K':K, 'vol':vol, 'T2':T2, 'T1':T1} integrate(x, w, a, **kwargs) |
这是在它出错之前打印的
1 | {'F': 1.2075, 'flag': -1.0, 'K': 0.12509999999999999, 'T2': 0.068500000000000005, 'vol': 0.42999999999999999, 'T1': 0.041099999999999998} |
以及错误,尽管上面定义了k:
1 | NameError: name 'K' is not defined |
解决方案是定义每个输入,而不是从字典中提取每个值…传递给最后一个函数的
例如。:
1 2 3 4 5 6 7 8 9 10 | kwargs = {'K': 1} def foo(**kwargs): print(K) def bar(**kwargs): print(kwargs['K']) foo(**kwargs) # NameError bar(**kwargs) # Works Ok. |