考虑以下Python3代码,我在其中定义函数f(t)^ 2并区分它:
import sympy as sp
def differentiate(func):
return func.diff(arg)
fct = sp.symbols('f', cls=sp.Function)
arg = sp.symbols('t')
expr = fct(arg) ** 2
print(differentiate(expr)) # returns 2*f(t)*Derivative(f(t), t)
我的问题是,为什么没有必要也将Python变量arg
的名称传递给differentiate
函数?
(我只传递了表达式expr
,我认为这是一个对象为我创造的对象。方法差异如何应用于此知道arg
?)
答案 0 :(得分:3)
我认为这只是错误的代码,因为它依赖于全局变量arg
,而它应该是differentiate
的参数之一。例如,如果您将此变量称为argument
,则该功能将无效。
此代码有效,因为arg
是全局变量,可供任何函数访问。所以,口译员会看到'在函数中使用名称arg
并询问自己:"在本地范围内是否有一个名为arg
的变量?" - 不; " 全局范围内是否有一个名为arg
的变量?" - 是的所以,它需要它并作为参数传递给func.diff
。
答案 1 :(得分:1)
To the other answer I would add that this has nothing to do with SymPy. This is just how Python works. If a function references a variable that isn't defined in that function, it gets it from the outer namespace where the function is defined (you can search this site or the web for "Python scoping" for more information about this).
This "worked" because you also used the variable name arg
for symbols('t')
. In general, I would recommend naming SymPy variables the same as their symbol name, so instead of arg
, use
t = symbols('t')
You will avoid a lot of headache if you always do this.