In: Computer Science
Please, how to construct a class template in Python?
Class name is animal:
give it a set of class variables called: gender, status
give it a set of class private variables: __heart, __lungs, __brain_size
construct methods to write and read the private class variables
in addition initiate in the constructor the following instance variables: name, location as well as initiate the variables status and gender all from constructor parameters
The variables meaning is as follows:
name is name
status is wild or domestic
location is location
gender is gender (M/F)
Private variables have all values Yes or NO only __brain_size should be a number
Be sure to provide a check on every variable that requires it.. Yes/No variables can only get values Yes/NO, Numeric variables only number. The rest does not need a check.
Finally provide a method that will print the class state on the output such as
Animal Name: Name
Animal Location: location
etc (print all parameters with the appropriate description)
All variables that you are initializing will depend on the user
Python code pasted below.
#class Definition
class animal:
#Constructor
def __init__(self,name,location,gender,status):
self.name=name
self.location=location
self.gender=gender
self.status=status
#display animal details
def displayAnimal(self):
print("Animal name:",self.name)
print("Location:",self.location)
print("Gender:",self.gender)
print("Status:",self.status)
#method for getting values of private variables
#private variables are declared with preceeding 2 double underscore
def getParam(self,heart,lungs,brain):
self.__heart=heart
self.__lungs=lungs
self.__brain_size=brain
#method for displaying values of private variables
#private variables are declared with preceeding 2 double
underscore
def displayParam(self):
print("Heart:",self.__heart)
print("Lungs:",self.__lungs)
print("Brain size:",self.__brain_size)
#main program
#creating animal object and invoking the constructor
a=animal("Lion","Africa","M","wild")
#calling displayAnimal() method for displaying the animal
attributes
a.displayAnimal()
#calling getParam to pass values to private variables in animal
class
a.getParam("Yes","Yes",20)
#calling displayParam() to display the values of private variables
in animal class
a.displayParam()
Python code in IDLE pasted for better understanding of the indent.
Output Screen