0

I have two classes for making pyqt5 windows. Inside class one I have a button with a function it is connected to.

Class One:

from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow

class MainWindow(QMainWindow): def init(self): super(MainWindow, self).init()

    self.btn = QtWidgets.QPushButton(self)
    self.btn.setText('Button')

    self.btn.clicked.connect(self.func)

def func(self):
    # ...

In class two, I have the same button and need the function, but I don't want to copy and paste code.

Class Two:

class OtherWindow(QtWidgets.QDialog):
    def __init__(self):
        super(OtherWindow, self).__init__()
    self.btn = QtWidgets.QPushButton(self)
    self.btn.setText('Button')

    # want the function but don't want to copy/paste

Would it be considered "bad practice" to do this? If so, what can I do instead?

1 Answers1

4

If you want an example of calling the same function in two different classes without having to define it twice you already have one in the code provided:

self.btn = QtWidgets.QPushButton(self)

Actually you have two:

self.btn.setText('Button')

So the real question is, should you do that or just copy and paste the 9 lines?

Well there is a principle to consider here. Don't Repeat Yourself (DRY). But be sure you understand it before you apply it. I've talked about it before.

Some think DRY is something a static analysis tool can check just by looking for identical code. This is wrong because what we care about is spreading around places where code will have to change together. The principle (or admonition) that checks against this goes: "Make decisions in one place".

When someone cracks this encryption, and we have to update it, how hard are you making it to find everywhere it needs to be fixed?

If, however, the code just happens to look the same but it represents two different ideas that are free to be changed independently then copy as you like. Makes it easier to change independently anyway. Just be sure you're making these separate ideas clear somehow. Or the next coder is gonna refactor them into one because they don't know any better.

candied_orange
  • 119,268