【发布时间】:2016-12-16 00:08:56
【问题描述】:
在 Python 3.5 中,对象如何调用实例化它的对象中的函数?
我创建了一个 PyQt 应用程序,它实例化了一个简单的数据库对象 db。我希望 db 对象能够更新主窗口对象中的进度条,但我无法弄清楚传递给 db 对象的内容以使其成为可能。
我花了几个小时在线阅读,但无法弄清楚这一点。我以为我可以将 self 作为 MainWindow 对象的标识符传递给 db 对象,但是在 db =photoDb(self) 失败并出现 NameError:“名称'self'未定义”。显然,尽管阅读了很多关于它的网页或网页,但我并不完全理解 self。
我怀疑这一定是构造函数中的简单信息传递,但我想不通。 (而且我已经花了几个小时阅读可能与此相关的 StackOverflow 条目。抱歉,如果这应该是显而易见的,或者已经在我没有找到的条目中得到了回答。)我正在使用 Python 3.5、PyQt4 和 Ubuntu 16.10。
我的代码要点:
class photoDb(self, mainwindow):
def __init__(self):
self.db = []
def addPhotosToDb(self, filenames):
i = 0
for f in filenames:
(do a bunch of stuff here with f)
self.db.append(f)
mainwindow.updateProgressBar(int(100*i/len(filenames))
class MainWindow(QtGui.QMainWindow, photoOrg_MainWindow.Ui_MainWindow):
db =photoDb(self)
def __init__(self):
super(self.__class__, self).__init__()
self.setupUi(self)
(lots more GUI widget connection code here)
def updateProgressBar(self, percentage):
self.progressBar.setValue(percentage)
def addPhotosToDb(self):
self.db.addPhotosToDb(listOfFiles) #the list is gotten from a dialog box generated elsewhere in the mainwindow class code
def main():
app = QtGui.QApplication(sys.argv)
form = MainWindow()
form.show()
app.exec_()
if __name__ == '__main__':
main()
【问题讨论】: