A Code Question Concerning Polymorphism
What follows is an example, in code, of polymorphism:
from abc import ABC, abstractmethod class UIControl(ABC): @abstractmethod def draw(self): pass class TextBox(UIControl): def draw(self): print("Draw TextBox") class DropDownList(UIControl): def draw(self): print("Draw DropDownList") def draw(control): control.draw() ddl = DropDownList() tbox = TextBox() controls = [ddl, tbox] for control in controls: draw(control) print(isinstance(control, UIControl))
Here, UIControl is derived from ABC, an abstract class having an abstract draw() method. Later in the code, the draw function takes the parameter “control” and uses it to call the draw function of the control passed to it as a parameter to draw.
My question is: how is control an instance of UIControl when that isn’t declared anywhere. The output from the “isinstance” call returns “True” proving that the “control“ parameter is indeed an instance of UIControl. I just don’t see how. Can anyone help with this?
Both ddl and tbox are an instance of a class that are both subclasses of UIControl. Hence both ddl and tbox inherit from UIControl.