Stuck on why this is not working as expected
- Create a List using the ListModel
- Add 5 items to the list using the ItemModel I call it store. Items are stored in the store.items which is a list Each item is created with the ItemModel Object the object name is item Then each item is added to the items list in the store with store.add(id, name) i.e. store.add(1, 'Candy')
- When I go to save the records in the store object(ListModel). I loop through the list of items and run a error_check function in the ItemModel.
This issue is when I find a name that is None. It finds it and there is a false positive for every record aftewards.
Why is this happening?
Also I noted below on how I can fix it.
Output
Store Items
ID: 1, Candy
ID: 2, Pop
ID: 3, None
ID: 4, Milk
ID: 5, Meat
Save Items
ID: 1, Candy - No errors
[]
ID: 2, Pop - No errors
[]
ID: 3, None - No errors
['Name "None" is empty']
ID: 4, Milk - No errors
['Name "None" is empty'] <<<< Why is this showing the error from item 3?
ID: 5, Meat - No errors
['Name "None" is empty'] <<<< Why is this showing the error from item 3?
Code
class ListModel:
items = []
def add(self, id=None, name=None):
item = ItemModel(id, name)
# Add the item to the list of items
self.items.append(item)
def save(self):
for i in self.items:
# Check the Item for errors using the error_check function on the ItemModel
i.error_check()
if i.errors is not None:
print(f'ID: {i.id}, {i.name} - No errors')
print(i.errors)
else:
print(f'ID: {i.id}, {i.name} - Has errors')
print(i.errors)
class ItemModel:
id = None
name = None
errors = []
def __init__(self, id, name):
self.id = id
self.name = name
# The following line will fix the error.
# Why is the errors = [] from above not used?
# self.errors = []
def error_check(self):
if self.name is None:
self.errors.append(f'Name "{self.name}" is empty')
if __name__ == '__main__':
store = ListModel()
store.add(1, 'Candy')
store.add(2, 'Pop')
store.add(3, None)
store.add(4, 'Milk')
store.add(5, 'Meat')
print(f'Store Items')
for i in store.items:
print(f'ID: {i.id}, {i.name}')
print(f'\n')
print(f'Save Items')
store.save()