如果您想使用test_list,这是一个由other_window 方法创建的变量,来自test 的实例,您有几个选择。
假设您在某处全局定义了test 的实例,您可以调用need_list() 并将test_list 作为参数。例如:
class test(QtWidgets.QMainWindow):
def __init__(self, parent=None):
self.test.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect1)
def connect1(self):
window = other_window(self)
otherview.show()
def need_list(self, test_list):
print(test_list)
class other_window(QtWidgets.QMainWindow)
def __init__(self, parent=None):
self.other_window.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect2)
def connect2(self):
# do something
self.pushbutton.clicked.connect(self.return_list)
def return_list(self):
test_list = []
test_list.append("a", "b", "c")
return test_list
test_instance = test() # Or however you defined these
other_window_instance = other_window()
test_instance.need_list(other_window_instance.return_list())
您也可以将test_list 设为全局。这将需要以一定的灵活性为代价进行较少的更改:
class test(QtWidgets.QMainWindow):
def __init__(self, parent=None):
self.test.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect1)
def connect1(self):
window = other_window(self)
otherview.show()
def need_list(self):
print(test_list)
class other_window(QtWidgets.QMainWindow)
def __init__(self, parent=None):
self.other_window.setupUi(self) # QT
#do something
self.pushbutton.clicked.connect(self.connect2)
def connect2(self):
# do something
self.pushbutton.clicked.connect(self.return_list)
def return_list(self):
global test_list
test_list = []
test_list.append("a", "b", "c")
test_instance = test()
other_window_instance = other_window()
Python 具有可变范围(请参阅the Python documentation on execution),这意味着在您的原始程序中,need_list() 无法看到test_list,因为它是在本地定义的。该函数之外的任何内容都无法看到test_list,除非您将其声明为全局变量(在第二个选项中使用global关键字,这使得它可以在除重新分配给相同名称的函数体之外的任何地方看到. 请参阅this question 了解更多信息)或将其显式传递给函数(使用need_list() 中的函数参数,如第一个选项所示)。
希望这有帮助!