What is class hierarchy

 

A somewhat more difficult to understand, but particularly important property of object-oriented programming languages ​​is the polymorphism. This means the call of overwritten methods, whereby the call is automatically adapted to the class. A simple example shows you what is meant by this.

You use a list with the previously defined classes animals

animals = [Dog (), Dog (), Cat ()]

in which there are two dogs and a cat. When traversing the list and calling tell () With

for animal in animals: animal.tell ()

a difficulty arises because there are three different methods of tell (), namely one in each class Pet, Dog and Cat. The computer can resolve this ambiguity in three ways. He can

  1. issue an error message,
  2. the tell () the base class Pet call,
  3. find out what kind of pets it is and the corresponding one tell () call.

In a polymorphic programming language like Python, the last and best behavior applies.

 

from gamegrid import * from soundsystem import * # ---------------- class Animal ---------------- classAnimal (): def __init __ ( self, imgPath): self.imagePath = imgPath def showMe (self, x, y): bg.drawImage (self.imagePath, x, y) # ---------------- class Pet ---------------- classPet (Animal): def __init __ (self, imgPath, name): Animal .__ init __ (self, imgPath) self.name = name def tell (self, x, y): bg.drawText (self.name, Point (x, y)) # ---------------- class Dog ----------- ----- classDog (Pet): def __init __ (self, imgPath, name): Pet .__ init __ (self, imgPath, name) def tell (self, x, y): # Overridden Pet.tell (self, x, y) openSoundPlayer ("wav / dog.wav") play () # ---------------- class Cat ---------------- classCat (Pet): def __init __ (self, imgPath, name): Pet .__ init __ (self, imgPath, name) def tell (self, x, y): # Overridden Pet.tell (self, x, y) openS oundPlayer ("wav / cat.wav") play () makeGameGrid (600, 600, 1, False) setBgColor (Color.green) show () doRun () bg = getBg () animals = [Dog ("sprites / dog. gif "," Alex "), Dog (" sprites / dog.gif "," Rex "), Cat (" sprites / cat.gif "," Xara ")] y = 100 for animal in animals: animal.showMe ( 100, y) animal.tell (200, y + 30) # Which tell () ???? show () y = y + 200 delay (1000)
Mark the program code