{OOP Python} How to add multiple initialised strings into and append() method

So i'm working on a simple code that works like a bag, this code currently can read and add singular initialised strings into an array that has been also initialised under all classes. Here's the code:

class Items:
# This class initializes the items name
    def __init__(self, name):
        self.name = name

class Bag:
    # This class adds the initialised items and reads anything in the bag
    def __init__(self, items, max_items):
        # max_items is the maximum capacity of the Bag
        self.items = items
        self.max_items = max_items
    def add_items(self):
        if len(self.items) < self.max_items:
            self.items.append(i.name) # <- Here is the problem at '(i.name)'
    def read_items(self):
        for item in self.items:
i = Items("Item1")
i2 = Items("Item2")
b = Bag([], 10) # I'm just going to put example 10 strings for the max_items

The output of this code is "Item1".

I wanted the 'append()' method in 'add_items()' function to also add 'i2' initialisation and other initialisation that will be added in the future with any name that the user will put in automatically.

If anyone knows how to fix this, please help me write a simple code to fix the problem. Thanks!

Submitted July 21st 2021 by Admin


I think what you need is a list of items passed to your add_items function:

def add_items(self, items: list): if (len(self.items) + len(items)) < self.max_items: for i in items: self.items.append(i.name) 

Admin | 4 days ago

Relevant Questions