Polymorphism#

Polymorphism is a term used to describe the phenomenon of something appearing in multiple forms. In nature an example would be a dog. A dog can appear in different forms (breeds). It also means that multiple dog forms (breeds) are all derived from a common form - dog.

In the Object Oriented Programming (OOP), this means that an object might appear as either an instance of a its actual class or an instance of a superclass.

Let’s modify our original guide example:

 1import tkinter as tk
 2import tkinter.ttk as ttk
 3import tkclasswiz as wiz
 4
 5# Normal Python classes with annotations (type hints)
 6class Wheel:
 7    def __init__(self, diameter: float):
 8        self.diameter = diameter
 9
10class WinterWheel(Wheel):
11    pass
12
13class SummerWheel(Wheel):
14    pass
15
16
17class Car:
18    def __init__(
19        self,
20        name: str,
21        speed: float,
22        wheels: list[Wheel]
23    ):
24        self.name = name
25        self.speed = speed
26        self.wheels = wheels
27
28        if speed > 50_000:
29            raise ValueError("Car can go up to 50 000 km / h")
30
31        if len(wheels) != 4:
32            raise ValueError("The car must have 4 wheels!")
33
34# Tkinter main window
35root = tk.Tk("Test")
36
37# Modified tkinter Combobox that will store actual objects instead of strings
38combo = wiz.ComboBoxObjects(root)
39combo.pack(fill=tk.X, padx=5)
40
41def make_car(old = None):
42    """
43    Function for opening a window either in new definition mode (old = None) or
44    edit mode (old != None)
45    """
46    assert old is None or isinstance(old, wiz.ObjectInfo)
47
48    window = wiz.ObjectEditWindow()  # The object definition window / wizard
49    window.open_object_edit_frame(Car, combo, old_data=old)  # Open the actual frame
50
51def print_defined():
52    data = combo.get()
53    data = wiz.convert_to_objects(data)  # Convert any abstract ObjectInfo objects into actual Python objects
54    print(f"Object: {data}; Type: {type(data)}",)  # Print the object and it's datatype
55
56
57# Main GUI structure
58ttk.Button(text="Define Car", command=make_car).pack()
59ttk.Button(text="Edit Car", command=lambda: make_car(combo.get())).pack()
60ttk.Button(text="Print defined", command=print_defined).pack()
61root.mainloop()

We can see that two new classes are created - WinterWheel and SummerWheel. We also see that Car’s wheels parameter is still a list of type Wheel. TkClassWizard not only considers the annotated type when constructing a GUI, but also the annotated type’s subclasses, implementing the concept of polymorphism, thus allowing us definition of Wheel, WinterWheel and SummerWheel classes.

../_images/new_define_frame_list_polymorphism.png