# File: classes.py # Author: Dr. Gibson # Date: 5/8/2017 # Section: N/A # E-mail: k.gibson@umbc.edu # Description: # This file contains python code that uses # classes and inheritance # animal class ("parent" class) class animal: # __init__() is the constructor def __init__(self, species, name, age): self.species = species self.name = name self.age = age # __str__() is used when we print() an animal def __str__(self): msg = "This " + str(self.species) + " is named " + str(self.name) msg += " and is " + str(self.age) + " years old." return msg # speak() will print out the noise the animal makes def speak(self): print("\"" + str(self.species) + " noise\"") # dog inherits everything from animal # overrides: speak() # extends : __init__, __str__ class dog(animal): def __init__(self, name, age, breed): # calls parent class's constructor animal.__init__(self, "dog", name, age) # also initializes breed self.breed = breed def __str__(self): # get the result from parent __str__ msg = animal.__str__(self) # add information about the breed msg += "\n\tTheir breed is " + str(self.breed) return msg def speak(self): print(str(self.name) + " says boof!") # cat inherits everything from animal # overrides: speak() # no changes: __init__, __str__ class cat(animal): def speak(self): print(str(self.name) + " goes meow.") def main(): # create an animal object (species: sheep) variable1 = animal("sheep", "Dolly", 6) # can create objects of class dog and cat # can have each animal speak(), and can print() each animal # dog's constructor is overridden, and takes in different parameters dog1 = dog("True Grit", 50, "Chesapeake Bay Retriever") print(dog1) dog1.speak() print() # cat's constructor is NOT overridden, so it's the same as animal's cat1 = cat("cat", "Maru", 9) print(cat1) cat1.speak() print() main()