Question

Need help finishing this code # Description : The Pet class contains fields for name, pet...

Need help finishing this code
# Description : The Pet class contains fields for name, pet
# type,and age. The age field is the age now
# or age of pet when it passed away. (These
# are all dogs I have had.) There is a static or
# class variable called number_pets that
# tracks how many instances have been created.
# The constructor will fill all fields and add
# one to the number_pets variable.
# The special method __str__ will return a
# string with formatting. The special
# method __lt__ will determine whether the
# object's age is less than the other's age
# which will enable the sort method to work.
# A list of pets is created, sorted, and
# printed in main.
#
# STUDENT INSTRUCTIONS
#
# 1. Read the Description above.
# 2. Replace the Last and First in program name and author.
# 3. Create attributes/fields/instance variables (they are all
# the same thing, but I'll call them fields in the rest of
# this assignment) in the constructor called __init__ for
# name of type string, pet_type of type string, and age of
# type int,and set them to the parameters by the same name.
# Remember to put self and the dot operator in front of
# the field names.
# 4. Add one to the number_pets class variable. Remember to put
# the class name in front of it with the dot operator.
# 5. Run the program to make sure it works. If not, fix it
# before moving on. You will get this:
# <__main__.Pet object at 0x0557C050>
# You have instantiated 1 pet.
# That first line is rather cryptic, so we'll fix that
# with the next step.
# 6. The __str__ method is a special method that you can use
# for printing a class instance the way you want. It is
# currently returning its default. Change this so that it
# returns a string that will look like this when printed
# (but don't actually print anything within the method):
# Allie : Pomeranian , Age: 2
# Both string fields should be left-justified, the name
# should take 10 characters,the pet_type 16 characters. age,
# which is an int should be right-justified
# and take 4 digits.
# 7. Run the program and make sure it works.
# 8. Fix the method called human_age_equivalent. Instead of
# returning 0, return 7 * the age field. Remember to put self
# and the dot operator in front of age.
# 9. Add ", Human Equivalent: " and human_age_equivalent to the
# __str__ method so that you will print:
# Allie : Pomeranian , Age: 2, Human Equivalent: 14
# 10.Run the program and make sure it works.
# 11.Remove the """ before the line pets = list() and the """
# after the line: print("\nYou have instantiated %d pets." %
Pet.number_pets)
# Run the program and make sure it works.
# 12.Define the less-than operator < for the class by changing
# the __lt__ method. We want to define one pet is less than
# another using the instance's age. So change the line from
# return True to returning the appropriate thing. The sort
# method for lists uses the less-than method,
# so it is the only operator we need to define to call sort.
# 13.Remove the """ before # sort the pets list by age
# and remove the one before the call to main().
# 14.Run the program and make sure it works.
# 15.Add at least 3 more pets to the list. Run the program and
# make sure it works. If your pet_name or name exceeds
# the sizes stated for __str__, you may increase either of
# them as needed. Run the program and make sure it works.
# 16.You are finished, so take your screenshot and prepare
# to submit.

class Pet:
# static class variables
number_pets = 0

# constructor
def __init__(self, name="", pet_type="", age=0):
# instance variables
# FIX ME #3.
# FIX ME #4.

# special method for converting to a string
def __str__(self):
# FIX ME #6.
return super().__str__()

# regular instance method
def human_age_equivalent(self):
# FIX ME #8.
return 0

# define < so that we can sort instances by age in a list
def __lt__(self, other):
# FIX ME #12.
return True

def main():

allie = Pet()
allie.name = "Allie"
allie.pet_type = "Pomeranian"
allie.age = 2
print(allie)
print("\nYou have instantiated %d pets." % Pet.number_pets)

# Remove the next line with """ for #11.
"""
pets = list()
pets.append(allie)
pets.append(Pet("Zack", "Toy Fox Terrier", 10))
pets.append(Pet("Charlie", "Fox Terrier Mix", 12))
pets.append(Pet("Wishbone", "Wire Fox Terrie", 11))
pets.append(Pet("Twinkle", "Keyshound", 13))
pets.append(Pet("Sandy", "Terrier Mix", 15))
pets.append(Pet("Snowball", "American Eskimo", 9))
# FIX ME: #15

print("\nOriginal Order\n")
for pet in pets:
print(pet)
print("\nYou have instantiated %d pets." % Pet.number_pets)
"""
# Remove the previous line with """ for #11.

# Remove the next line with """ for #13.
"""
# sort the pets list by age
pets.sort()

print("\nSorted Order\n")
for pet in pets:
print(pet)
print("\nYou have instantiated %d pets." % Pet.number_pets)
"""
# Remove the previous line with """ for #13.

main()
input("Press Enter when finished reading output.")

0 0
Add a comment Improve this question Transcribed image text
Answer #1

'''
Python version : 3.6
Python program to create and test Pet class
'''
class Pet:
   # static class variables
   number_pets = 0
  
   # constructor
   def __init__(self, name="", pet_type="", age=0):
       # instance variables
       self.name = name
       self.pet_type = pet_type
       self.age = age
       Pet.number_pets += 1
      
   # special method for converting to a string
   def __str__(self):
      
       return ('%-10s:%-16s , Age: %4d , Human Equivalent: %4d' %(self.name,self.pet_type,self.age,self.human_age_equivalent()))
      
   # regular instance method
   def human_age_equivalent(self):
      
       return 7*self.age
      
   # define < so that we can sort instances by age in a list
   def __lt__(self, other):
       return self.age < other.age
      
def main():
   allie = Pet()
   allie.name = "Allie"
   allie.pet_type = "Pomeranian"
   allie.age = 2
   print(allie)
   print("\nYou have instantiated %d pets." % Pet.number_pets)
  
   pets = list()
   pets.append(allie)
   pets.append(Pet("Zack", "Toy Fox Terrier", 10))
   pets.append(Pet("Charlie", "Fox Terrier Mix", 12))
   pets.append(Pet("Wishbone", "Wire Fox Terrie", 11))
   pets.append(Pet("Twinkle", "Keyshound", 13))
   pets.append(Pet("Sandy", "Terrier Mix", 15))
   pets.append(Pet("Snowball", "American Eskimo", 9))
   pets.append(Pet("Fluffy","Fox Hound Mix",5))
   pets.append(Pet("Rocky","Terrier Terrie",13))
   pets.append(Pet("Jasmine","Pomeranian",8))
  
   print("\nOriginal Order\n")
   for pet in pets:
       print(pet)
   print("\nYou have instantiated %d pets." % Pet.number_pets)
  
   # sort the pets list by age
   pets.sort()
   print("\nSorted Order\n")
   for pet in pets:
       print(pet)
   print("\nYou have instantiated %d pets." % Pet.number_pets)

#call the main function  
main()
input("Press Enter when finished reading output.")  
#end of program

Code Screenshot:

Output:

Add a comment
Know the answer?
Add Answer to:
Need help finishing this code # Description : The Pet class contains fields for name, pet...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • 9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name,...

    9p This is for Python I need help. Pet #pet.py mName mAge class Pet: + __init__(name, age) + getName + getAge0 def init (self, name, age): self.mName = name self.mAge = age Dog Cat def getName(self): return self.mName mSize mColor + __init__(name, age,size) + getSize() + momCommento + getDog Years() +_init__(name, age,color) + getColor + pretty Factor + getCatYears def getAge(self): return self.mAge #dog.py import pet #cat.py import pet class Dog (pet. Pet): class Cat (pet. Pet): def init (self,...

  • USE PYTHON CODING ####################### ## ## Definition for the class Pet ## ######################## class Pet: owner=""...

    USE PYTHON CODING ####################### ## ## Definition for the class Pet ## ######################## class Pet: owner="" name="" alive=False def __init__(self,new_name): self.name=new_name self.alive=True Using the code shown above as a base write a code to do the following: - Create a separate function (not part of the class) called sameOwner which reports whether two pets have the same owner. test it to be sure it works - Add a variable age to Pet() and assign a random value between 1 and...

  • 11) What ten values would be printed if the following code was run? write your answer...

    11) What ten values would be printed if the following code was run? write your answer in the correct order 11a to 11j class Pat(): def__init__(self, name, age): self._name = name self._age = age def __str__(self): return "Pet: +self._name+ " "+str(self._age) def getName(self): return self._name def getAge(self): return self._age def setName(self,newName): self._age =newAge def incrementAge(self): self._age = self._age +1 pet1 = Pet ("Fluffy" ,5) pet2 = Pet ("Spot", 2) print (pet1) print (Pet.__doc__) pet2.setName("Dot") print(pet2.getAge()) pet1.incrementAge() print(pet1.getAge()) pet2.setAge(4) print(Pet.getName.__doc__) f...

  • Using Python you will create a simple class pet which will contain: Type of pet (a...

    Using Python you will create a simple class pet which will contain: Type of pet (a string) Name of pet(a string) Age of pet (an int) Tricks (a list of tricks the pet can perform) Fleas of pet (an int) All of these data attributes except for the last one (fleas) will be unique to each object. The fleas will be common to all pets, as they like to travel. In your main part of your program, you will create...

  • To do: Now add code to Pet and PetPlay to complete the comments in the code....

    To do: Now add code to Pet and PetPlay to complete the comments in the code. import java.util.ArrayList; public class PetPlay {    //-----------------------------------------------------------------    // Stores and modifies a list of pets    //----------------------------------------------------------------- public static void main (String[] args)    { // always make your array lists generic ArrayList pets = new ArrayList(); pets.add(new Pet("dog", "Bella")); pets.add(new Pet("cat","Blackie")); pets.add(new Pet("bird", "Babs")); pets.add(new Pet("dog", "Lassie")); pets.add(new Pet("horse", "Sam")); pets.add(new Pet("dog", "Blackie")); pets.add(new Pet("turtle", "Joe")); pets.add(new Pet("bird","Annie")); pets.add(new Pet("bird", "Alex"));...

  • Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born...

    Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born which is a subclass of Famous_Person. Add a method to calculate the day of the week the person was born and print out all of the corresponding information using the overridden print method. Use the following code below as a starting point. ////////////////////////////////////////////////////// from datetime import datetime class Famous_Person(object): def __init__(self, last, first, month,day, year): self.last = last self.first = first self.month = month...

  • I need help with the adding the following to my python code (also provided below) M5A6Part2...

    I need help with the adding the following to my python code (also provided below) M5A6Part2 ⦁   When a user successfully votes, add the user’s voterID to the _voterIDsVoted list ⦁   When a user successfully votes, increment the value of the variable that counts the votes for the candidate the user voted for. This would be either _candidateAVotes or _candidateBVotes Hint: run your original test code again. If you reused a valid voter ID in your tests it should cause...

  • python * important *

    In this question, you will complete the FootballPlayer class, which is used to  compute some features of a Football Player. The class should be constructed with the name and age, as well as shooting, passing, tackling and saving skill  points of a player. The constructor method as well as the defenderScore method  is provided below. You should implement the remaining methods. The definitons  of the methods are presented below as comments.  An example execution and the corresponding outputs are provided below: >>> burkay = FootballPlayer("Burkay", 42, 15, 30, 10, 15) >>> cemil = FootballPlayer("Cemil", 30, 70, 30, 45, 20) >>> ronaldo = FootballPlayer("Ronaldo", 36, 85, 95, 35, 5) >>> print(burkay) (Burkay,42,13640000) >>> print(cemil) (Cemil,30,144270000) >>> print(ronaldo) (Ronaldo,36,322445000) >>> print(burkay > cemil) False >>> print(ronaldo > burkay) True """ class FootballPlayer:     def __init__(self, na, ag, sh, pa, ta, sa):         # age is in [18,40]         # skills are in [10,100]         self.name = na         self.age = ag         self.shooting = sh         self.passing = pa         self.tackling = ta         self.saving = sa     def defenderScore(self):         # The defensive score is defined as 80% tackling, 15% passing and 5% shooting         # It should be reported as integer         return int(0.80 * self.tackling + 0.15 * self.passing + 0.05 * self.shooting)     def midfielderScore(self):         # The midfielder score is defined as 50% passing, 25% shooting and 25% tackling         # It should be reported as integer         return # Remove this line to answer this question     def forwardScore(self):         # The forward score is defined as 70% shooting, 25% passing and 5% tackling         # It should be reported as integer         return # Remove this line to answer this question     def goalieScore(self):         # The goalie score is defined as 90% saving and 10% passing         # It should be reported as integer         return # Remove this line to answer this question     def playerValue(self):         # Player value is defined as          # * 15000$ per unit of the square of defensive score         # * 25000$ per unit of the square of midfielder score         # * 20000$ per unit of the square of forward score         # * 5000$ per unit of the square of goalie score         # * -30000$ per (age-26)^2         # A player's value is never reported as negative. The minimum is 0.         # It should be reported as integer         return # Remove this line to answer this question     def __str__(self):         # This method returns a string representation of the player, such as         # "(name,age,playerValue)"         return # Remove this line to answer this question     def __gt__(self, other):         # This method returns True if the player value of self is greater than          # the player value of other. Otherwise, it returns False.         return # Remove this line to answer this question

  • Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born which is a subclass of Famous_Person. Add a method to calculate the day of the week the person was born...

    Write a program that does the following in Python Code: Write a new Class called Famous_Day_Born which is a subclass of Famous_Person. Add a method to calculate the day of the week the person was born and print out all of the corresponding information using the overridden print method. Use the following code below as a starting point. ////////////////////////////////////////////////////// from datetime import datetime class Famous_Person(object): def __init__(self, last, first, month,day, year): self.last = last self.first = first self.month = month...

  • Type up the GeometricObject class (code given on the back of the paper). Name this file Geometric...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT