I'm working on a Python project in which I have to represent a GUI-structure in my code. It looks like this:
- window1 (containing button1, button2, button3, dialog1, ...)
- window2 (containing button4, button5, dialog2, list1, ...)
So there is a number of windows, each with different content, and different functionality behind the different elements. Each window can have different custom methods that should work only there.
Now I have two possibilities:
The first:
class Window1(object):
def __init__(self):
self.elements = {"button1":button1,"button2":button2,...}
def customMethod(self):
print "do custom"
class Window2(object):
def __init__(self):
self.elements = {"button4":button4,"button5":button5,...}
def otherCustomMethod(self):
print "do other custom"
...
window1 = Window1()
window2 = Window2()
But if I do this, there will be many classes, one for each window, and I only need one instance of each window. So the second possibility would be to create the right objects on the fly:
# create template class
class WindowGeneric(object):
pass
# create first window
window1 = WindowGeneric()
window1.elements = {"button4":button4,"button5":button5,...}
def customMethod(self):
print "do custom"
window1.customMethod = customMethod.__get__(window1, WindowGeneric) #bind to instance
#create second window
window2 = WindowGeneric()
window2.elements = {"button4":button4,"button5":button5,...}
def otherCustomMethod(self):
print "do other custom"
window1.otherCustomMethod = otherCustomMethod.__get__(window2, WindowGeneric) #bind to instance
But this solution looks ugly, too, because of the get "hacking" stuff.
It's really all about the creation of the objects, the elements of the windows is known before runtime and will not change during runtime.
So is there any better way to do this?
Edit: To clarify things a bit: I only want to create a lot of similar but not equal objects (they can have different methods and vars inside), but I don't know if it is better to create a new class for every object (version 1) or to create the objects by having a dummy object and adding the individual functionality afterwards (version 2).