Object-oriented programming for one instance

I have been into low-level programming for decades, but never really got into object-oriented programming (OOP) until I started using Python. And that concept made it difficult for me to learn how to write a Python GUI with PyQt.

A very simple example of a PyQt GUI on the web would look like this:

import sys
from PyQt5 import QtCore, QtWidgets

app = QtWidgets.QApplication(sys.argv)

class Window(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.init_ui()

    def init_ui(self):
        self.btn = QtWidgets.QPushButton("Close")
        self.btn.clicked.connect(self.close)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.btn)
        self.setLayout(layout)
        self.show()

window = Window()

app.exec_()

What I really did not understand is why I need to create a class for a GUI interface that I will only use once? Only later did I find out that it is possible to accomplish the same task without creating a class, like this:

import sys
from PyQt5 import QtCore, QtWidgets

app = QtWidgets.QApplication(sys.argv)

window = QtWidgets.QWidget()

window.btn = QtWidgets.QPushButton("Close")
window.btn.clicked.connect(window.close)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(window.btn)
window.setLayout(layout)
window.show()

app.exec_()

In my opinion as an unprofessional programmer, creating classes is very useful when you need many instances of the same object. I have even used some kind of proto-classes in plain C when I was communicating with multiple instances of the same chip. But creating a class for a single object really makes little sense and is even confusing when learning new concepts.

Created by Marko Pinteric.

Updated . Web page has been read by visitors since May 2024.