Exercise
Array Of Tables And Coffee Tables
Objective
Develop a Python project called "Tables2," extending the "Tables" project.
In this project, define a class called "CoffeeTable" that inherits from the "Table" class. In addition to displaying the table’s width and height, the "ShowData" method should also print "(Coffee table)."
Create an array with 5 tables and 5 coffee tables. The tables should have random dimensions between 50 and 200 cm, while the coffee tables should range from 40 to 120 cm. Display the details for all the tables and coffee tables in the array.
Example Python Exercise
Show Python Code
import random
# Class for Table
class Table:
def __init__(self, width, height):
self.width = width # Width of the table
self.height = height # Height of the table
# Method to display table information
def show_data(self):
print(f"Table dimensions: {self.width} cm x {self.height} cm")
# Class for CoffeeTable (inherits from Table)
class CoffeeTable(Table):
def __init__(self, width, height):
super().__init__(width, height) # Call the constructor of the parent class (Table)
# Override the show_data method to include "(Coffee table)" label
def show_data(self):
print(f"Table dimensions: {self.width} cm x {self.height} cm (Coffee table)")
# Main function to create and display tables and coffee tables
def main():
tables = [] # List to store tables
coffee_tables = [] # List to store coffee tables
# Create 5 tables with random dimensions between 50 and 200 cm
for _ in range(5):
width = random.randint(50, 200) # Random width between 50 and 200 cm
height = random.randint(50, 200) # Random height between 50 and 200 cm
table = Table(width, height)
tables.append(table)
# Create 5 coffee tables with random dimensions between 40 and 120 cm
for _ in range(5):
width = random.randint(40, 120) # Random width between 40 and 120 cm
height = random.randint(40, 120) # Random height between 40 and 120 cm
coffee_table = CoffeeTable(width, height)
coffee_tables.append(coffee_table)
# Display the details for all the tables and coffee tables
print("Tables:")
for table in tables:
table.show_data()
print("\nCoffee Tables:")
for coffee_table in coffee_tables:
coffee_table.show_data()
# Run the main function
if __name__ == "__main__":
main()
Output
Tables:
Table dimensions: 150 cm x 112 cm
Table dimensions: 160 cm x 183 cm
Table dimensions: 79 cm x 106 cm
Table dimensions: 186 cm x 188 cm
Table dimensions: 104 cm x 121 cm
Coffee Tables:
Table dimensions: 95 cm x 55 cm (Coffee table)
Table dimensions: 108 cm x 70 cm (Coffee table)
Table dimensions: 66 cm x 102 cm (Coffee table)
Table dimensions: 107 cm x 111 cm (Coffee table)
Table dimensions: 56 cm x 97 cm (Coffee table)
Share this Python Exercise