I am going in a circle over and over trying to write a "supermarket" application using OOP.
The app should be useful for the employees of a supermarket. The app reads data from a CSV file which looks like this:
name,amount
soap,4
rice,5
bread,10
The supermarket has cashiers and managers. Cashiers should only be able to view the amount for a product. Managers can view but also change an amount.
Here's the code I came up with:
import pandas
class Data:
"""Creates a pandas dataframe out of a text file"""
def __init__(self, datafile = "products.txt"):
self.datafile = datafile
def get_dataframe(self):
df = pandas.read_csv("products.txt", index_col = "name")
return df
def save_to_csv(self):
df = pandas.read_csv("products.txt", index_col = "name")
df.to_csv(self.datafile)
print(df)
class Product:
"""Represent a product from the dataframe table"""
def __init__(self, name, dataframe = Data().get_dataframe()):
self.name = name
self.dataframe = dataframe
def get_amount(self):
"""Return the available amount of the product object taken from the dataframe"""
return self.dataframe.loc[self.name, "amount"]
def add_amount(self, amount, password):
"""Changes the dataframe by adding an amount to the existing amount"""
if password == 1234:
self.dataframe.loc[self.name, "amount"] += amount
data = Data()
data.save_to_csv()
print("Saved")
else:
return "You're not a manager"
def remove_component(self, person):
"""Changes the dataframe by removing an amount from the existing amount"""
if password == 1234:
self.dataframe.loc[self.name, amount] -= 1
else:
return "You're not a manager"
def __del__(self):
"""Delete the dataframe from memory when Product is destroyed"""
del self.dataframe
Data().save_to_csv()
I think the authentication layer is very poorly implemented here. I simply added a conditional in the add and remove methods. Is there any better way to do the authentication part?
Should I also create Manager and Cashier classes in case I expand the program later. For example, adding info about salaries for managers and cashiers. That would require to have Manager and Cashier objects I guess.
Will the code load many Data objects? Should I use a singleton for the Data object?
What other design pattern could I have used for this app?
I am going in a circle over and over trying to [...]andWill the code load many Data objects?sound like the code is either not done/working or you don't understand it. Perhaps rewording the question can help. \$\endgroup\$