Python - How to save functions(Python - 如何保存函数)
问题描述
我从 python 开始.我有四个功能并且工作正常.我要做的就是拯救他们.我想在 python 中随时调用它们.
I´m starting in python. I have four functions and are working OK. What I want to do is to save them. I want to call them whenever I want in python.
这是我的四个函数的代码:
Here's the code my four functions:
import numpy as ui
def simulate_prizedoor(nsim):
sim=ui.random.choice(3,nsim)
return sims
def simulate_guess(nsim):
guesses=ui.random.choice(3,nsim)
return guesses
def goat_door(prizedoors, guesses):
result = ui.random.randint(0, 3, prizedoors.size)
while True:
bad = (result == prizedoors) | (result == guesses)
if not bad.any():
return result
result[bad] = ui.random.randint(0, 3, bad.sum())
def switch_guesses(guesses, goatdoors):
result = ui.random.randint(0, 3, guesses.size)
while True:
bad = (result == guesses) | (result == goatdoors)
if not bad.any():
return result
result[bad] = ui.random.randint(0, 3, bad.sum())
推荐答案
你要做的是把你的 Python 文件作为一个模块或者一个库强>.
What you want to do is to take your Python file, and use it as a module or a library.
没有办法让这四个功能自动可用,无论如何,100% 的时间,但你可以做一些非常接近的事情.
There's no way to make those four functions automatically available, no matter what, 100% percent of the time, but you can do something very close.
例如,在文件顶部,您导入了 numpy.numpy 是一个已设置好的模块或库,因此只要您 import 它,您就可以在任何时候运行 python 时使用它.
For example, at the top of your file, you imported numpy. numpy is a module or library which has been set up so it's available any time you run python, as long as you import it.
您也想做同样的事情——将这 4 个函数保存到一个文件中,并在需要时随时导入.
You want to do the same thing -- save those 4 functions into a file, and import them whenever you want them.
例如,如果您将这四个函数复制并粘贴到名为 foobar.py 的文件中,那么您可以简单地执行 from foobar import *.但是,这仅在您在保存代码的同一文件夹中运行 Python 时才有效.
For example, if you copy and paste those four functions into a file named foobar.py, then you can simply do from foobar import *. However, this will only work if you're running Python in the same folder where you saved your code.
如果你想让你的模块在系统范围内可用,你必须把它保存在 PYTHONPATH 的某个地方.通常,将其保存到 C:Python27Libsite-packages 即可(假设您运行的是 Windows).
If you want to make your module available system-wide, you have to save it somewhere on the PYTHONPATH. Usually, saving it to C:Python27Libsite-packages will work (assuming you're running Windows).
这篇关于Python - 如何保存函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 如何保存函数
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
