Need help with Intro to Computer Science 2 Python problem Im
Need help with Intro to Computer Science 2 (Python) problem:
Implement an exception class InvalidAge() for the Animal class implemented in the second lab and found in the template file. In addition to writing the InvalidAge class you must modify the setAge() method of the Animal class to check if the age provided as a parameter is negative. If it is, it raises an InvalidAge exception. It should raise the exception before any object variables are modified. If the age is positive or zero, it should set the age of the animal to the specified parameter. The constructor should be modified in a similar way so that Animal objects with negative ages cannot be created.
This is what we are given in the template file:
The following demonstrates how the classes could be used when completed (with appropriate edits to the output to not give away the answer to the problem:
#Modified Animal class with InvalidAge exception for negative ages class InvalidAge (Exception) pa 33 class Animal #modify init def init self newspecies default newLanguage default newAge 0) if newAge 0: raise Invalid Age else: self species new species self. language newLanguage self-age newAge def repr self return Animal (\'f)\',\' H)) format (self. species self. language self.age) def eq (self otherAnimal. return self. species otherAnimal species and self. language other Animal language and self.age other Animal .age def setSpecies (self, new species) self species new Species def setLanguage (self, new Language self language newLanguage #modify setAge def setAge (self, newAge self-age newAge def speak (self) print (\"I am a year-old f and I f) format (self.age, self. Species self language))Solution
class InvalidAge( Exception):
    pass
class Animal:
    def __init__(self, newSpecies=\"default\", newLanguage=\"default\", newAge=0):
        if newAge<0:
            raise InvalidAge(\'%d is an invalid age\' %(newAge)) #modified
       
        else:
            self.species = newSpecies
            self.language = newLanguage
            self.age = newAge
   def __repr__(self):
        return \"Animal(\'{}\',\'{}\',{})\".format(self.species, self.language, self.age)
   def __eq__(self, otherAnimal):
        return self.species == otherAnimal.species and self.language == otherAnimal.language and self.age == otherAnimal.age
   def setSpecies(self, newSpecies):
        self.species = newSpecies
   def setLanguage(self, newLanguage):
        self.language = newLanguage
   def setAge(self, newAge):
        if newAge<0:
            raise InvalidAge(\'%d is an invalid age\' %(newAge))#modified
        else:
            self.age = newAge
   def speak(self):
        print(\"I am a {} year-old {} and I {}.\".format(self.age, self.species, self.language))

