We've talked about __init__(), we've talked about __str__(), but something we haven't talked about are two of the most important parts in the object world. Just two big words, and those words are polymorphism and inheritance.
Polymorphism: >= 2
Polymorphism means you can have at least 2 methods that are the same in different classes that do different things. Confused? Here's an example, and look at the function getArea().
So, if you wanted to do geometry, here's an example of finding the area.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
area = self.width * self.height
return area
class Cube:
def __init__(self, size):
self.size = size
def getArea(self):
area = self.size * self.size * self.size
return area
RectArea = Rectangle(5, 8)
CubeArea = Cube(4)
Now run the program, and type this in:
>>> RectArea.getArea()
40
>>> CubeArea.getArea()
64
>>>
Ta-da! Both classes used getArea(), but did different things and had different outcomes. That is polymorphism.
Next time, we will study inheritance. Brace yourself, these articles will never be simple again!
No comments:
Post a Comment