您可以从函数中返回它:
class MyClass():
data = some_data
def test(self):
for i in data:
if data is this:
data[1] = something
if data is that:
data[1] = something
else:
data[1] = something else
return data
在 中test2.py
,抓住并将其放在某处:
from test1 import MyClass
my_instance = MyClass()
data = my_instance.test()
print(data[1])
备选方案 1
将其作为变量放入MyClass
:
class MyClass():
data = some_data
def test(self):
for i in self.data:
if self.data is this:
self.data[1] = something
if data is that:
self.data[1] = something
else:
self.data[1] = something else
在 中test2.py
,将其作为 的属性my_instance
:
from test1 import MyClass
my_instance = MyClass()
my_instance.test()
print(my_instance.data[1])
备选方案 2
如果您想独立运行这两个脚本,您可以test1
将数据放在可以通过test2
. 例如,在一个文件中:
class MyClass():
data = some_data
def test(self):
for i in data:
if data is this:
data[1] = something
if data is that:
data[1] = something
else:
data[1] = something else
with open('data.txt', 'w') as f:
f.writelines(data)
现在,您可以轻松地从第二个脚本中获得它:
with open('data.txt') as f:
data = f.readlines()
print (data[1])
实现这一点并不难。
希望这可以帮助!