Use of csv file and mulitiple inheritance demo

This commit is contained in:
Donald Calloway 2025-09-24 08:43:03 -07:00
parent 8c5914826b
commit 6e52dba27b
4 changed files with 165 additions and 0 deletions

53
Dog.py Normal file
View File

@ -0,0 +1,53 @@
import random
class Dog:
def __init__(self, name, breed, FavActivity=None):
self.name = name
self.breed = breed
self.initialSetFavFood()
print(f"Woof! I'm {self.name}, a {self.breed}")
def initialSetFavFood(self):
self.FavFood = random.choice(['chicken', 'beef', 'lamb', 'fish'])
def getFavoriteFood(self):
return self.FavFood
def setFavoriteFood(self, newFavFood):
if newFavFood == "chips":
print("This is not a suitable food for me!")
else:
self.FavFood = newFavFood
class Labrador(Dog):
def __init__(self, name):
super().__init__(name, "Labrador")
self.initialSetFavFood()
self.FavActivity = "running"
def initialSetFavFood(self):
self.FavFood = random.choice(['rabbit', 'cat', 'lamb'])
def setFavoriteActivity(self, newFavActivity):
self.FavActivity = newFavActivity
def getFavActivity(self):
return self.FavActivity
myLabrador = Labrador("Rex")
myLabrador.setFavoriteFood("chips")
print(f"My favorite food is {myLabrador.getFavoriteFood()} and my favorite activity is {myLabrador.getFavActivity()}")
class Bulldog(Dog):
def __init__(self, name):
super().__init__(name, "bulldog", "sleeping")
self.initialSetFavFood()

View File

@ -0,0 +1,80 @@
import csv
class Product:
pay_rate = 0.8 # Class variable for a standard discount of 20%
all = []
def __init__(self, name, price, quantity):
assert price >= 0, f"Product price {price} is not greater than or equal to zero!"
assert quantity >= 0, f"Product quantity {quantity} is not greater than or equal to zero!"
self.name = name
self.price = price
self.quantity = quantity
# Action to execute
Product.all.append(self) # Store all instances in the class variable 'all'
def calculate_total_price(self):
return self.price * self.quantity
def apply_discount(self):
return self.calculate_total_price() * (self.pay_rate)
def __repr__(self):
return f"Product('{self.name}', {self.price}, {self.quantity})"
@classmethod
def instantiate_from_csv(cls):
with open('items.csv', 'r') as f:
reader = csv.DictReader(f)
items = list(reader)
for item in items:
try:
name = item.get('name')
price_str = item.get('price')
quantity_str = item.get('quantity')
if name is None or price_str is None or quantity_str is None:
raise ValueError(f"Missing data in row: {item}")
price = float(price_str)
quantity = int(quantity_str)
Product(name, price, quantity)
print(f"Created: {name}, ${price:.2f}, {quantity}")
except (TypeError, ValueError) as e:
print(f"Skipping row due to error: {item}{e}")
# Example usage:
if __name__ == "__main__":
Product.instantiate_from_csv() # Instantiate products from the CSV file
print("All Products", Product.all) # Print all instances stored in the class variable 'all'
'''
for instance in Product.all:
if instance.name in ["Smartphone", "Monitor", "Keyboard"]:
instance.pay_rate = 0.7 # Special discount of 30%
elif instance.name == "Tablet":
instance.pay_rate = 1.0 # No discount
else:
instance.pay_rate = 0.8 # Standard discount of 20%
total_price = instance.calculate_total_price()
discounted_price = instance.apply_discount()
print(f"Product: {instance.name}, Total Price: ${total_price:.2f}, Price after Discount: ${discounted_price:.2f}")
print(repr(instance)) # Print the formal representation of the instance
print(Product.all) # Print all instances stored in the class variable 'all'
'''

9
items.csv Normal file
View File

@ -0,0 +1,9 @@
name,price,quantity
"apple",0.50,100
"banana",0.30,150
"orange",0.80,200
"grape",2.00,50
"mango",1.50,75
"kiwi",1.20,60
"peach",1.00,80
1 name price quantity
2 apple 0.50 100
3 banana 0.30 150
4 orange 0.80 200
5 grape 2.00 50
6 mango 1.50 75
7 kiwi 1.20 60
8 peach 1.00 80

23
mult_inheritance.py Normal file
View File

@ -0,0 +1,23 @@
class Flyable:
def fly(self):
return "Flying high!"
class Swimmable:
def swim(self):
return "Swimming deep!"
class Duck(Flyable, Swimmable):
def __init__(self, name):
self.name = name
d = Duck("Donald")
print(f"{d.name} is {d.fly()} and {d.swim()}")
# Output:
# Donald is Flying high! and Swimming deep!
# Demonstrates multiple inheritance where Duck inherits from both Flyable and Swimmable classes.
# The Duck class can use methods from both parent classes.
# The order of inheritance matters; methods are resolved in the order of the base classes listed.
# In this case, Flyable is checked before Swimmable for method resolution.