I subclass Frame
and Label
in Tkinter
in order to automatically .pack()
them (this is just a usage example, my question is not strictly related to Tkinter). The definitions are the same for both classes except for the labels:
class Frame(tk.Frame):
def __init__(self, parent, **kwargs):
objparams, packparams = dispatch_parameters(self, **kwargs)
tk.Frame.__init__(self, parent, objparams)
self.pack(packparams)
class Label(tk.Label):
def __init__(self, parent, **kwargs):
objparams, packparams = dispatch_parameters(self, **kwargs)
tk.Label.__init__(self, parent, objparams)
self.pack(packparams)
In order not to repeat the same code for these two classes I am wondering how to reuse it by just varying the "label". I am aware that "Frame
" above means different things within the class (a class name, an actual class, ...) so I am trying to understand if it is correct to look at something along the lines of (this is pseudo-code to try to explain my point)
for classname in ["Frame", "Label"]:
class <<classname>>(tk.<<classname>>):
def __init__(self, parent, **kwargs):
objparams, packparams = dispatch_parameters(self, **kwargs)
tk.<<classname>>.__init__(self, parent, objparams)
self.pack(packparams)
Is there a pythonic approach to such cases of code reuse? Or should I stick with defining classes one after the others, even if the code is very similar?
Note 1: I believe this question is very similar to another one, but for objective-c
Note 2: I deliberately omitted the tkinter
tag as the example I gave is just a specific instance of a general case