Search code examples
pythonclassoopmodel-view-controllerinstance

what is the difference between `c = Controller(model, view)` and `Controller(model, view)` in python?


I encontered a situation in my code and doubt it. I have a code like this:

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()

but this wouldn't work as expected. I did this and it worked:

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()

notice that I am not using the c variable. what I don't understand is what is the difference in the code, I am calling the controller and I think it should work, what I am missing here?

I searched it but I want to gain some insight about the internal work of it.


Solution

  • When you don't affect it to a variable, the "Controller" is destroy (I guess it's the way Python works) Here a simple exemple you can run to see the difference:

    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()
    

    Console output :

    TEST 1 => CREATE
    TEST 1 => DESTROY
    TEST 2 => CREATE