Understanding Polymorphism


Polymorphism is the quality of being able to treat different types of things in the same way. Polymorphism is usually associated with OOP, but you've seen it in action before. The len() function is polymorphic because it works with different types, such as strings, tuples, or lists. For example, the following calls to len() all produce valid results even though each argument is of a different type:

 >>> len("How long am I?") 14 >>> len((1, 2, 3, 4, 5)) 5 >>> len(["a", "b", "c"]) 3 

Used in the context of OOP, polymorphism means that you can send the same message to objects of different classes related by inheritance and achieve different results. For example, the Unprintable_Card is derived from Card, but when you invoke the __str__() method of an Unprintable_Card object, you get a different result than when you invoke the __str__() method of a Card object. This means that you can print an object even if you don't know if it's an Unprintable_Card or a Card object. Regardless of the class of the object, when printed, its __str__() method is invoked and a string representation of it is displayed.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net