# # Example of inheritance -- basic animal classes with error checking # # Matt Bishop, MHI 289I, Fall 2023 # # # base class: animal # class Animal: # expected to be one of these kindofanimal = [ "lion", "bear", "dog", "giraffe", "cat" ] def __init__(self, kind): # if it's in the list, OK -- otherwise disallow it if kind in Animal.kindofanimal: self.kind = kind else: self.kind = None def __str__(self): # if it's not in the list, say so if self.kind: return "Your animal is a " + self.kind else: return "Your animal is of an unknown type" # # now the subclass, as cat is an animal # class Cat(Animal): # breeds of cats catbreed = [ "Persian", "Manx", "Siamese", "domestic" ] def __init__(self, breed): # instatiate as an animal super().__init__("cat") # add in the new attribute if breed in Cat.catbreed: self.breed = breed else: self.breed = None def __str__(self): # if it's not in the list, say so if self.breed: return super().__str__() + "; breed is "+self.breed else: return super().__str__() + "; the breed is unknown" # # nw the example usage # # first, the class -- show a lion a = Animal("lion") print(a) # then, the class -- show a tiger aa = Animal("tiger") print(aa) # now, the subclass, with a valid breed c = Cat("Persian") print(c) # and the subclass with an invalid breed c2 = Cat("Himalayan") print(c2) c3 = Animal("cat") print(c3)