Write a class named pet, which should have the following data attributes, __name
ID: 3688105 • Letter: W
Question
Write a class named pet, which should have the following data attributes,
__name (for the name of a pet)
__animal_type (for the type of animal that a pet is. Example values are 'Dog', 'Cat', and 'Bird')
__age (for the pet's age)
The pet class should have an __init__ method that creates these attributes. It should also have the following methods:
set_name
This method assigns a value to the __name field.
set_animal_type
This method assigns a value to the __animal_type field.
set_age
This method assigns a value to the __age_field.
get_name
This method returns the value of the __animal_type field.
get_animal_type
This method returns the value of the __animal_type field.
get_age
This method returns the value of the __age field.
Once you have written the class, write a program that creates an object of the class and prompts the user to enter the name, type, and age of his or her pet. This data should be stored as the object's attributes. Use the object's accessor method to retrieve the pet's name, type, and age and display this data on the screen.
In pythong language please.
Explanation / Answer
#this code use python 3
#define pet and method
class pet(object):
#main init method
def __init__(self, name, animal_type,age):
self.set_name(name)
self.set_animal_type(animal_type)
self.set_age(age)
#get pet's name
def get_name(self):
return self.__name
#get pet's age
def get_age(self):
return self.__age
#get pet's type
def get_animal_type(self):
return self.__animal_type
#set name of a pet
def set_name(self, name):
self.__name = name
#set type of a pet
def set_animal_type(self, animal_type):
self.__animal_type = animal_type
#set age
def set_age(self, age):
self.__age = age
# user input onr by one
#if you want use lower then 3 then change user input method with raw_input
name = input("Please enter name of a pet: ")
pet_type = input("Please enter type of animal that a pet is: ")
age = input("Please enter pet's age: ")
# create class objest and pass pets infromation
instance = pet(name,pet_type,age)
# get details
print (instance.get_name()) # gives according to input
print (instance.get_animal_type()) # gives according to input
print (instance.get_age()) # gives according to input
# if you want set value one by one then use blow code
instance.set_name('labra')
instance.set_age('5')
instance.set_animal_type('dog')
# after set value we get value one by one
print (instance.get_name())
print (instance.get_age())
print (instance.get_animal_type())
# output last three method is labra, 5, dog
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.