Exercise
Table, Coffee Table, And Legs
Objective
Develop a python project based on the tables and coffee tables example, but now introduce a new class named "Leg". This class should have a method called "ShowData" that prints "I am a leg" followed by the data of the table it is attached to.
In the project, select one of the tables, add a leg to it, and call the "ShowData" method of that leg to display the details. This will allow you to demonstrate how the leg is associated with a table and how it can access and display the table's information.
Example Python Exercise
Show Python Code
import random
class Table:
def __init__(self, width, height):
"""
Constructor that initializes the width and height of the table.
"""
self.width = width
self.height = height
# ShowData method to display the dimensions of the table
def ShowData(self):
print(f"I am a table, my width is {self.width} cm and my height is {self.height} cm")
class CoffeeTable(Table):
def ShowData(self):
"""
Overrides the ShowData method from Table, adding the type of table.
"""
print(f"I am a coffee table, my width is {self.width} cm and my height is {self.height} cm")
class Leg:
def __init__(self, table):
"""
Constructor that initializes the leg with the table it is attached to.
"""
self.table = table
def ShowData(self):
"""
Displays the data of the table the leg is attached to.
"""
print(f"I am a leg, attached to a table with width {self.table.width} cm and height {self.table.height} cm")
# Test program
if __name__ == "__main__":
# Create a table and a coffee table with random dimensions
table = Table(random.randint(50, 200), random.randint(50, 200))
coffee_table = CoffeeTable(random.randint(40, 120), random.randint(40, 120))
# Show the details of the table and coffee table
print("Table Details:")
table.ShowData()
print("\nCoffee Table Details:")
coffee_table.ShowData()
# Create a leg for the table
leg_for_table = Leg(table)
print("\nLeg Details (for Table):")
leg_for_table.ShowData()
# Create a leg for the coffee table
leg_for_coffee_table = Leg(coffee_table)
print("\nLeg Details (for Coffee Table):")
leg_for_coffee_table.ShowData()
Output
Table Details:
I am a table, my width is 187 cm and my height is 151 cm
Coffee Table Details:
I am a coffee table, my width is 100 cm and my height is 104 cm
Leg Details (for Table):
I am a leg, attached to a table with width 187 cm and height 151 cm
Leg Details (for Coffee Table):
I am a leg, attached to a table with width 100 cm and height 104 cm
Share this Python Exercise