【问题标题】:How to import variable from another function and another directory?如何从另一个函数和另一个目录导入变量?
【发布时间】:2020-06-09 13:48:04
【问题描述】:

我有两个文件。

first.py

Class Repo:
   def my_function:
     variable = []

现在,我在不同的目录中有第二个文件,想要创建类似的内容:

second.py

def my_second_function(variable):
  print(variable) # or some other operations on variable

我可以做些什么来使上面的代码正常工作?我试过类似的东西:

import sys
sys.path.insert(1, 'path')
from first import *

但它不起作用。你有什么想法吗?

【问题讨论】:

  • 您是否对这个问题进行了网络搜索?这可能会有所帮助:stackoverflow.com/questions/4383571/…
  • 是的,我看到了,但没有帮助。
  • sys.path.insert 怎么不起作用?你有错误吗?抱歉,我忽略了 variablemy_function 中定义的事实。因此,除非您将其设为 global 变量,否则它可以在函数中访问。
  • 但是如何将此变量转换为全局变量?我认为,“全局变量”是不够的。
  • 你能提供一些你想如何使用变量的上下文吗?由于您似乎定义了一些类,您可以将变量作为类或其实例的属性吗?

标签: python function variables import directory


【解决方案1】:

虽然我并不完全清楚您的目标是什么,但这是一种在一个文件中定义全局变量的方法,然后可以通过您尝试的 sys.path 方法导入:

test_dir/file1.py:

global_var1 = 'global_var1' # This variable is available upon import of file1.py
def fun():
    global global_var2
    global_var2 = 'global_var2' # This variable will be available after having called fun()

file2.py:
import sys
sys.path.insert(1, 'test_dir')
import file1

print(file1.global_var1)
#print(file1.global_var2) # This would fail
file1.fun()
print(file1.global_var2) # This works

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-21
    • 2022-07-01
    • 2015-11-21
    • 1970-01-01
    • 2014-02-05
    • 1970-01-01
    相关资源
    最近更新 更多