Exercise10
Exercise10
Exercise10
1. Add a copy method to Book Class. Do no use the Python Copy library.
.
(5 points)
class Book:
def change_number_of_copies(self,update_amount):
self.copies += update_amount
def __str__(self):
return self.title + " by " + self.author + \
" with " + str(self.copies) + " copies."
class Book:
def __init__(self, title, author, copies):
self.title = title
self.author = author
self.copies = copies
def __str__(self):
return self.title + " by " + self.author + " with " + str(self.copies) + " copies."
# Copy method
def copy(self):
return Book(self.title, self.author, self.copies)
# Example usage
book1 = Book("1984", "George Orwell", 5)
book2 = book1.copy()
print(book1) # Output: 1984 by George Orwell with 5 copies.
print(book2) # Output: 1984 by George Orwell with 5 copies.
2. Using the Car class shown below, add a class attribute (make sure it is private) to keep track
of the number of car objects created and a static method that will return this value. Create
three objects of this type. Use the static method to show that three car objects have been
created.
(5 points)
class Car:
#Constructor
def __init__(self, make, model, mpg):
self.make = make
self.model = model
self.mpg = mpg
def __str__(self):
return self.make + " " + self.model + \
" gets " + str(self.mpg) + " miles to the gallon"
class Car:
# Private class attribute
_car_count = 0
# Constructor
def __init__(self, make, model, mpg):
self.make = make
self.model = model
self.mpg = mpg
Car._car_count += 1 # Increment car count when a new object is created
def __str__(self):
return self.make + " " + self.model + " gets " + str(self.mpg) + " miles to the gallon."
print(Car.get_car_count()) # Output: 3
3. Create a Textbook class that is a subclass (child class) of Book. It should have one additional
instance variable - subject. There should be the following methods:
(5 points)
a. The constructor which calls the superclass (parent classes)’s constructor to set the Parent
instance variables and then sets the subject
b. A method to calculate a fine (which takes the number of days as a parameter, multiplies it by
10 and then adds 1.00 to the fine)
c. __str__ method which calls the parent __str__ method and then adds on the subject
Test all methods
class Textbook(Book):
def __init__(self, title, author, copies, subject):
# Call the parent class constructor
super().__init__(title, author, copies)
self.subject = subject
# Example usage
textbook = Textbook("Physics for Scientists and Engineers", "Raymond Serway", 3,
"Physics")
print(textbook) # Output: Physics for Scientists and Engineers by Raymond Serway with 3
copies. (Subject: Physics)
print(f"Fine for 3 days late: ${textbook.calculate_fine(3):.2f}") # Output: Fine for 3 days
late: $31.00