[英]How to call functions from a file in Python?
I am very new to Python.我对 Python 很陌生。 I've learned recently that we could store all our defined functions in one file and call them up when we need it.
我最近了解到,我们可以将所有定义的函数存储在一个文件中,并在需要时调用它们。 I'm using Idle on Windows.
我在 Windows 上使用空闲。
Where should I store the.py file that will contain all the functions so they can be accessed from Idle, and how should I call it?我应该将包含所有函数的 .py 文件存储在哪里,以便可以从 Idle 访问它们,我应该如何调用它?
Some Folder
|
- my_funcs.py
|
- other.py
other.py 其他
from my_funcs import somefunc
somefunc("An Argument")
my_funcs.py my_funcs.py
def somefunc(s):
print "SomeFunction:%s"%s
then run other.py 然后运行other.py
The file must be on your PYTHONPATH. 该文件必须在您的PYTHONPATH上。 You need to set that in your environment.
您需要在您的环境中进行设置。 eg if your file is:
例如,如果您的文件是:
C:/path/to/myfile.py
Then you need to make sure that C:/path/to
is on PYTHONPATH. 然后,您需要确保
C:/path/to
在PYTHONPATH上。 Then, in another script, you can import myfile
via: 然后,在另一个脚本中,您可以通过以下方式导入
myfile
:
import myfile
Now you can use a function ( func
) defined in myfile
as: 现在,您可以将在
myfile
定义的函数( func
)用作:
myfile.func()
Say you are testing a function and you would like to see it working on the fly: this is the usual sequence假设您正在测试 function 并且您希望看到它在运行中运行:这是通常的顺序
Now it is 2 cases:现在是2种情况:
That is what it all should be.这就是一切。
Comment .评论。 Differently from compiling and testing in C, where you only need a text-editor to compile through Command line and a compiler (to avoid opening clunky dev-env's);
与 C 中的编译和测试不同,您只需要一个文本编辑器即可通过命令行和编译器进行编译(以避免打开笨重的 dev-env); in Python paradoxically such a workflow turns even too demanding to be an alternative to the native IDLE as you need to be specific each time.
在 Python 中,矛盾的是,这样的工作流程变得过于苛刻,无法替代原生 IDLE,因为您每次都需要具体。 I hope it helps
我希望它有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.