Python - 如何保存函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20938456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:36:00  来源:igfitidea点击:

Python - How to save functions

pythonfunctionsave

提问by CreamStat

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.

我从 python 开始。我有四个功能并且工作正常。我要做的就是拯救他们。我想在 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())

采纳答案by Michael0x2a

What you want to do is to take your Python file, and use it as a moduleor a library.

您想要做的是获取您的 Python 文件,并将其用作模块

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.

无论如何,没有办法让这四个功能在 100% 的时间内自动可用,但您可以做一些非常接近的事情。

For example, at the top of your file, you imported numpy. numpyis a module or library which has been set up so it's available any time you run python, as long as you importit.

例如,在文件的顶部,您导入了numpy. numpy是一个模块或库,它已经设置好,所以只要你导入它,它就可以在你运行 python时使用。

You want to do the same thing -- save those 4 functions into a file, and import them whenever you want them.

您想要做同样的事情——将这 4 个函数保存到一个文件中,并在需要时导入它们。



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.

例如,如果您将这四个函数复制并粘贴到名为 的文件中foobar.py,那么您只需执行from foobar import *. 但是,这仅在您在保存代码的同一文件夹中运行 Python 时才有效。

If you want to make your module available system-wide, you have to save it somewhere on the PYTHONPATH. Usually, saving it to C:\Python27\Lib\site-packageswill work (assuming you're running Windows).

如果你想让你的模块在系统范围内可用,你必须将它保存在PYTHONPATH 的某个地方。通常,将其保存为C:\Python27\Lib\site-packages可以工作(假设您运行的是 Windows)。

回答by Robert Christie

Save them in a file - this makes them a module.

将它们保存在一个文件中——这使它们成为一个模块

If you put them in a file called mymod.py, in python you can load them as follows

如果将它们放在名为 mymod.py 的文件中,则在 python 中可以按如下方式加载它们

from mymod import *
simulate_prizedoor(23)

回答by Victor Palade

If you decide to put them anywhere in your project folder don`t forget to create a blank init.py file so python can see them. A better answer can be provided here : http://docs.python.org/2/tutorial/modules.html

如果您决定将它们放在项目文件夹中的任何位置,请不要忘记创建一个空白的init.py 文件,以便 python 可以看到它们。可以在此处提供更好的答案:http: //docs.python.org/2/tutorial/modules.html

回答by DBCerigo

Quick solution, without having to explicitly create a file - relies on IPython and its storemagic

快速解决方案,无需显式创建文件 - 依赖于 IPython 及其storemagic

IPython 4.0.1 -- An enhanced Interactive Python.
details.

In [1]: def func(a):
   ...:     print a
   ...:     

In [2]: func = _i #gets the previous input

In [3]: store func #store(magic) the input 
                   #(auto-magic enabled or would need '%store')
Stored 'func' (unicode)

In [4]: exit

IPython 4.0.1 -- An enhanced Interactive Python.

In [1]: store -r func #retrieve stored string

In [2]: exec func #execute string as python code

In [3]: func(10)
10

Once you had stored all your functions just once, then you can restore them all with store -r, and then exec funconce for each function, in each new session.

将所有函数存储一次后,您可以使用 将它们全部恢复store -r,然后exec func在每个新会话中为每个函数恢复一次。

(Came across this question while looking for a solution for 'quick saving' functions (most convenient way) while in an interactive python session - adding my current best solution for future readers)

(在交互式 python 会话中寻找“快速保存”功能的解决方案(最方便的方法)时遇到了这个问题 - 为未来的读者添加我当前的最佳解决方案)