python 中的 `c = Controller(model, view)` 和 `Controller(model, view)` 有什么区别?

问题描述 投票:0回答:1

我在代码中遇到了一种情况并对此表示怀疑。 我有这样的代码:

def main():
    app = QApplication(sys.argv)
    view = View()
    db_name = 'db/main.db'
    model = Model(db_name)
    Controller(model, view)  # Connect the model and the view using the controller
    
    view.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

但这不会按预期工作。 我这样做了并且有效:

def main():
    app = QApplication(sys.argv)
    view = View()
    db_name = 'db/main.db'
    model = Model(db_name)
    c = Controller(model, view)  # Connect the model and the view using the controller
    
    view.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

请注意,我没有使用

c
变量。我不明白的是代码有什么区别,我正在调用控制器,我认为它应该可以工作,我在这里缺少什么?

我搜索了它,但我想了解它的内部工作原理。

python class oop model-view-controller instance
1个回答
0
投票

当你不影响变量时,“控制器”就会被销毁 (我猜这就是Python的工作方式) 这是一个简单的示例,您可以运行来查看差异:

from  PySide6.QtWidgets import QApplication
import sys

class Test():
    def __init__(self, id):
        self.id = id
        print("TEST " + str(self.id) + " => CREATE")

    def __del__(self):
        print("TEST " + str(self.id) + " => DESTROY")

def main():
    app = QApplication(sys.argv)
    Test(1)
    c = Test(2)
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

控制台输出:

TEST 1 => CREATE
TEST 1 => DESTROY
TEST 2 => CREATE
© www.soinside.com 2019 - 2024. All rights reserved.