Python - 如何保存函数

2022-01-24 00:00:00 python function save

问题描述

我从 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).

相关文章