Python Object-Oriented Python Advanced Objects Emulating Built-ins

Andrew Bickham
Andrew Bickham
1,461 Points

Inventory

class Item:
    def __init__(self, name, description, *args, **kwargs):
        self.name = name
        self.description = description

        for key, value in kwargs.items():
            setattr(self, key, value)

    def __str__(self):
        return '{}: {}'.format(self.name, self.description)


class Inventory(Item):
    def __init__(self):
        super().__init__("cheese", "cheesey")
        self.slots = []

    def __add__(self, item):
        self.slots.append(items)

    def __len__(self):
        return len(self.slots)

    def __contains__(self, item):
        return item in self.slots

    def display(self, item):
        print(item in inventories)

I was trying to display all the items that were passed into self.slots but no matter what I try all it returns in NONE, and im not sure why, if someone could please advise.... I do appreciate it

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 57,144 Points

Not sure of your goal, you could use:

    # display all items:
    def display(self):
        print(self.slots)

    # OR, print only if item in slots
    def display(self, item):
        if item in self:
            print(item)
        # add else for what happens 
        # if item not found

Post back if you need more help. Good luck!!!

Andrew Bickham
Andrew Bickham
1,461 Points

my apologies i kinda posted this in a rush, but i was messing around with kenneth's coding, i wanted to make it where someone could pass in multiple items into self.slots and then was able to see(display), everything they had passed in; i keep getting NONE returned every time i tried to view everything that was passed in to self.slots and of course i was curious to why, sorry for any confusion

Chris Freeman
Chris Freeman
Treehouse Moderator 57,144 Points

The __add__ method has no return statement so the default is return None.

To see what was added you could print or return the item from the __add__ method

If you wanted to handle multiple items added at once, you would need logic to check if item isinstance of str (then add it), if not string then loop through item adding each member. If you were to loop over item when it was a string then each character would be added.

Is this what you were looking for?

Andrew Bickham
Andrew Bickham
1,461 Points

yes thank you, once again my apologies for the confusion