简体   繁体   English

在 function 内的全局表达式中替换一个局部值

[英]Substitute a local value in the global expression inside a function

I want to substitute some parameters inside the function (i) without creating additional parameters of the function f(parameters), (ii) without changing variables globally.我想替换 function (i) 中的一些参数而不创建 function f(parameters) 的附加参数,(ii) 而不全局更改变量。 The problem is that one variable is defined outside the function and I would like to keep it this way (z can be potentially a result of many other preceding cells).问题是在 function 之外定义了一个变量,我想保持这种方式(z 可能是许多其他先前单元格的结果)。

import sympy
x_hh=sympy.Symbol("x_hh") 
z=x_hh+2;

def v():
    x_hh=2;
    a=1;
    utility = a*z
    return utility
display(v())

As the output I have x_hh+2 , but I want to have 4 .作为 output 我有x_hh+2 ,但我想有4

Your code will be interpreted from up to down.您的代码将从上到下进行解释。 So z=x_hh+2;所以z=x_hh+2; will only be called once at the beginning.只会在开始时调用一次。

you could simply create a new variable inside the funciton:您可以简单地在函数内创建一个新变量:

import sympy
x_hh=sympy.Symbol("x_hh") 
z=x_hh+2

def v():
    x_hh=2; #the value of x_hh was changed here
    new_var = x_hh+2 # this variable will be up-to-date and won't affect z
    a=1;
    utility = a*new_var #we use the new variable instead of z
    return utility
display(v())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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