Polymorphism is a somewhat polymorph concept in CS. When it comes to OO, it mainly means 'polymorphic type-based dispatch', which means that the concrete implementation of a method / resolution of an attribute will be selected at runtime based on the object's type. As an example:
class Foo(object):
def do_this(self):
return 42
class Bar(object):
def do_this(self):
return 84
def whatever(*objects):
for obj in objects:
print obj.do_this()
objects = [Foo(), Bar()]
whatever(*objects)
The point is that I can now create a new class:
class Baaz(object):
def do_this(self):
return -1
and pass it to whatever()
without having to modifiy whatever()
:
whatever(Baaz())
whatever()
works with any object having a do_this(self)
method, and the correct implementation of do_this()
is automagically selected by being looked up on the object itself.
Compare this with pure procedural code:
def foo_do_this(foo):
return 42
def bar_do_this(bar):
return 84
def whatever(*objects):
for obj in objects:
if obj.__class__.__name__ == "Foo":
print foo_do_this(obj)
elif obj.__class__.__name__ == "Bar":
print bar_do_this(bar)
else:
print "dont know how to handle '%s', sorry" % (obj.__class__.__name__)
which requires that I edit whatever()
to accomodate any new implementation of xxx_do_this()
.
And no, this isn't a "good example of polymorphism in Tkinter, because I never use Tkinter - but if you understand the above example you should be able to spot quite a few examples of polymorphism in Tkinter as well as in almost any Python module or package.