【问题标题】:Importing functions from separate file python从单独的文件python导入函数
【发布时间】:2023-03-30 00:56:01
【问题描述】:

我正在尝试将函数从一个文件导入另一个文件。

例如 在我的文件'main.py'中,我有以下代码:

from helper_funcs import *
a = 10
print(square())

在我的文件“helper_funcs.py”中,我有以下代码:

def square():
  return a*a

显然这不起作用,因为我的“helper_funcs.py”文件中没有定义“a”。它可能与命名空间有关。有没有一种方法可以在我的主文件中将此函数与变量一起使用?

我不想将变量 'a' 作为参数传递。

【问题讨论】:

  • a作为参数传递给square,并将square的定义改为square(a)
  • 我知道。你应该这样做。这听起来像是一个 XY 问题。
  • “我不想将变量 'a' 作为参数传递。”——为什么不呢?这是正确的做法。
  • main.py 导入ahelper_funcs.py
  • 然后将其传递为kwargs 或其他东西。

标签: python python-3.x namespaces


【解决方案1】:

试试这个

你的函数保存为 square.py

def square(a):
  return a*a

在你的主代码中导入如下函数,但不要使用from square.py import square

from square import square
a = 10
print(square(a))

但是在这里你传递了变量 a

【讨论】:

    猜你喜欢
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多