简体   繁体   English

Python:在函数内调用外部函数

[英]Python: calling external functions within functions

I am new to Python, and am having a problem: I want to write a function ( Jacobian ) which takes a function and a point as arguments, and returns the jacobian of that function at the given point. 我是Python的新手,我遇到了一个问题:我想写一个函数( Jacobian ),它接受一个函数和一个点作为参数,并在给定的点返回该函数的jacobian

Unsurprisingly, Jacobian relies on NumPy and SciPy. 不出所料, Jacobian依赖于NumPy和SciPy。 When I call Jacobian from another script, I get either: 当我从另一个剧本中调用Jacobian ,我会得到:

  1. An error that says I cannot import a module into a function (when I have an import statement for NumPy/SciPy in Jacobian ) or 一个错误,表示我无法将模块导入函数(当我在Jacobian NumPy / SciPy的import语句时)或
  2. Errors that various NumPy/Scipy functions (eg zeros() ) are not defined, (when I omit the import statement to avoid the error mentioned above. 未定义各种NumPy / Scipy函数(例如zeros() )的错误(当我省略import语句以避免上述错误时)。

What am I doing wrong? 我究竟做错了什么?

Also, if someone knows of an implementation of Jacobian , that would be useful as well. 此外,如果有人知道Jacobian的实现,那也是有用的。 There doesn't seem to be one in SciPy. 在SciPy中似乎没有一个。

You can import at the module level and then use the imported names from inside any functions. 您可以在模块级别导入,然后使用任何函数内部的导入名称。 Or you can import any required names directly inside a function. 或者,您可以直接在函数内导入任何必需的名称。

There is one situation where you cannot use import inside a function: you are not allowed to do from somemodule import * because the Python compiler wants to know all of the local variables in the function and with import * it cannot tell in advance what names will be imported. 有一种情况你不能在函数中使用import :你不允许from somemodule import *from somemodule import *因为Python编译器想要知道函数中的所有局部变量并且使用import *它不能预先知道将使用什么名称进口。

The solution is simple: never use import * , always import exactly the names that you want to use. 解决方案很简单:永远不要使用import * ,始终完全导入您要使用的名称。

PS It helps if you copy the code that is giving the problem and the exact error message you are getting. PS如果您复制提供问题的代码以及您获得的确切错误消息,它会有所帮助。 I'm guessing here that this is your problem but you'll get faster and more accurate answers if you provide the relevant details. 我在这里猜测这是你的问题,但如果你提供相关细节,你会得到更快更准确的答案。

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

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