import pickle
class Table:
"""Represents a table with width and height."""
def __init__(self, width, height):
"""Initialize the table with width and height."""
self.width = width
self.height = height
def show_data(self):
"""Display the dimensions of the table."""
print(f"Width: {self.width}, Height: {self.height}")
class TableManager:
"""Manages a list of tables, including saving and restoring data."""
def __init__(self):
"""Initialize an empty list of tables."""
self.tables = []
def add_table(self, table):
"""Add a new table to the list."""
self.tables.append(table)
def dump_to_file(self, filename):
"""
Save the list of tables to a binary file.
:param filename: Name of the binary file.
"""
try:
with open(filename, 'wb') as file:
pickle.dump(self.tables, file)
print(f"Data successfully dumped to {filename}.")
except Exception as e:
print(f"Error while dumping to file: {e}")
def restore_from_file(self, filename):
"""
Load the list of tables from a binary file.
:param filename: Name of the binary file.
"""
try:
with open(filename, 'rb') as file:
self.tables = pickle.load(file)
print(f"Data successfully restored from {filename}.")
except Exception as e:
print(f"Error while restoring from file: {e}")
def show_all_tables(self):
"""Display data for all tables."""
for i, table in enumerate(self.tables, start=1):
print(f"Table {i}:")
table.show_data()
# Main Program
if __name__ == "__main__":
import random
# Initialize the TableManager
manager = TableManager()
# Create and add 10 tables with random dimensions
for _ in range(10):
width = random.randint(50, 200)
height = random.randint(50, 200)
manager.add_table(Table(width, height))
# Display all tables
print("Initial table data:")
manager.show_all_tables()
# Dump data to a binary file
filename = "tables_data.bin"
manager.dump_to_file(filename)
# Clear current tables
manager.tables = []
# Restore data from the binary file
print("\nRestoring data from file...")
manager.restore_from_file(filename)
# Display restored tables
print("\nRestored table data:")
manager.show_all_tables()
Output
Initial Table Data:
Initial table data:
Table 1:
Width: 120, Height: 180
Table 2:
Width: 150, Height: 75
...
After Restoring:
Restoring data from file...
Restored table data:
Table 1:
Width: 120, Height: 180
Table 2:
Width: 150, Height: 75
...