【问题标题】:How to call functions from a file in Python?如何在 Python 中从文件中调用函数?
【发布时间】:2023-03-03 22:09:01
【问题描述】:

我对 Python 很陌生。我最近了解到,我们可以将所有定义的函数存储在一个文件中,并在需要时调用它们。我在 Windows 上使用 Idle。

我应该将包含所有函数的 .py 文件存储在哪里,以便可以从 Idle 访问它们,我应该如何调用它?

【问题讨论】:

    标签: python windows module python-idle


    【解决方案1】:
    Some Folder
    |
      - my_funcs.py
    |
      - other.py
    

    其他.py

    from my_funcs import somefunc
    somefunc("An Argument")
    

    my_funcs.py

    def somefunc(s):
        print "SomeFunction:%s"%s
    

    然后运行 ​​other.py

    【讨论】:

      【解决方案2】:

      该文件必须在您的 PYTHONPATH 上。您需要在您的环境中进行设置。例如如果您的文件是:

      C:/path/to/myfile.py
      

      然后您需要确保 C:/path/to 在 PYTHONPATH 上。然后,在另一个脚本中,您可以通过以下方式导入myfile

      import myfile
      

      现在您可以将myfile 中定义的函数(func)用作:

      myfile.func()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-27
        • 2018-02-07
        • 2018-04-30
        相关资源
        最近更新 更多