python - 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. 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).
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
.
解决方案
您的代码将从上到下进行解释。所以z=x_hh+2;
只会在开始时被调用一次。
您可以简单地在函数内创建一个新变量:
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())
推荐阅读
- autohotkey - #IfWinActive / #ifWinExist 在 ahk 中未按预期工作
- c# - 起订量和多种方法设置
- javascript - Vuetify 使所有按钮变圆
- c# - 使用 TableEntity(Azure 表存储)的最佳实践——类的解耦
- python - 在 Anaconda 中安装 cdQA 的问题
- javascript - 字符串不可分配给 onMouseEvent
- python - Can't connect bot to discord
- linux - 如何查询rDNS?
- python - 在 Python 中循环查询 SPARQL
- python - NumPy - 根据字典替换矩阵中的值