【发布时间】: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 怎么不起作用?你有错误吗?抱歉,我忽略了
variable在my_function中定义的事实。因此,除非您将其设为global变量,否则它可以在函数中访问。 -
但是如何将此变量转换为全局变量?我认为,“全局变量”是不够的。
-
你能提供一些你想如何使用变量的上下文吗?由于您似乎定义了一些类,您可以将变量作为类或其实例的属性吗?
标签: python function variables import directory