Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Python OOP- Object not iterable and .pop() not working

I am creating a program where there are two classes. The first class contains a container (a list attribute) and some methods to work on the list.

The second class has an attribute which is an instance of this first class and another attribute which is a plain Python list. This class performs some operations on the object and the plain list.

class Foo:
    def __init__(self):
        self.container = []

    def addToContainer(self, x):
        self.container.append(x)

class Bar:
    def __init__(self):
        self.thing = Foo()
        self.main = []

    def __str__(self):
        return "This is the main: " + ", ".join(map(str, self.main))

    def doOperation(self):
        # An example operation to be performed
        for i in range(3):
            self.thing.addToContainer(i)

        # Now set main to the updated thing as a list
        self.main = self.thing

    def getLastOfMain(self):
        # Remove and get last item
        return self.main.pop()


test = Bar()
test.doOperation()
print(test)
print(test.getLastOfMain())

When running this I got an error for return "This is the main: " + ", ".join(map(str, self.main)):

TypeError: 'Foo' object is not iterable.

I looked around the internet and found out that I needed to make the Foo class have iterable properties for its objects, so I changed the code to this:

class Foo:
    def __init__(self):
        self.container = []

    ### Overrode the iter class ###
    def __iter__(self):
        return iter(self.container)

    def addToContainer(self, x):
        self.container.append(x)

class Bar:
    def __init__(self):
        self.thing = Foo()
        self.main = []

    def __str__(self):
        return "This is the main: " + ", ".join(map(str, self.main))

    def doOperation(self):
        # An example operation to be performed
        for i in range(3):
            self.thing.addToContainer(i)

        # Now set main to the updated thing as a list
        self.main = self.thing

    def getLastOfMain(self):
        # Remove and get last item
        return self.main.pop()


test = Bar()
test.doOperation()
print(test)
print(test.getLastOfMain()) # Error

But after fixing that I have now got one more error which I can't figure how to fix. A new error came from the line: return self.main.pop:

AttributeError: 'Foo' object has no attribute 'pop'.

I am attempting the get the last value of self.main which is a Python list NOT an object (I don't want it to be one). Yet the program thinks it is an object somehow.

How can I get self.main to perform the .pop() operation and behave like any other list?

Comments