I’ve been looking at some tutorials for some PyQt4 stuff and It Is Good, but I don’t quite understand why the syntax when creating an object is such:
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
#code to set up instance variables and show() the window
What is gained exactly from doing it in this way, and not just eliminating the self.initUI() call entirely and just putting any code that sets attributes in the __init__() after the super is called?
Sometimes code is separated into functions for readability purposes.
If your object initialization requires three steps, then logically it would make sense to break it into three functions. The names of those functions could describe which portion of the initialization they handle.
Another reason you might see an “init” function called from the true
__init__is if that function restores the object to a fresh state; in that case, you might want to call the “clean” function from outside__init__in, for example, an object pool.You’ve also hinted at a third reason for the reuse in your own question: if a subclass needs to change the order in which portions of the initialization happen (or omit/replace some portions entirely!) this is not possible with a monolithic
__init__but easy if it’s split into separate parts.A fourth and final reason is for profiling. If you track function entries/exists and timings, separate functions gives you finer granularity in the timing metrics.
Regardless, how you code is up to you – but the approach you question here does have merits.