Python Object-Oriented Python Advanced Objects Emulating Built-ins

daniel steinberg
daniel steinberg
12,976 Points

Sorted Inventory

I am trying to use the Sorted Inventory code from the quiz. The code runs fine with Inventory, but I get an error when using Sorted Inventory, which should inherit from Inventory:

True 2 sharp gold Traceback (most recent call last): File "override.py", line 54, in <module> inventory2.add_item(ring) File "override.py", line 36, in add_item self.slots.sort() TypeError: '<' not supported between instances of 'Item' and 'Weapon'

Can you help?

class Item: def init(self, name, description): self.name = name self.description = description

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

class Weapon(Item): def init(self, name, description, power): super().init(name, description) self.power = power

class Inventory:

def __init__(self):
    self.slots = []

def add_item(self, item):
    self.slots.append(item)

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

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

def __iter__(self):
    yield from self.slots   

class SortedInventory(Inventory): def add_item(self, item): super().add_item(item) self.slots.sort()

from items import Item, Weapon

sword = Weapon('sword', 'sharp', 50) coin = Item('coin', 'gold') inventory = Inventory() inventory.add_item(sword) inventory.add_item(coin) print(sword in inventory) print(len(inventory)) for item in inventory: print(item.description)

dagger = Weapon('dagger', 'sharper', 70) ring = Item('ring', 'silver') inventory2 = SortedInventory() inventory2.add_item(dagger) inventory2.add_item(ring) print(sword in inventory2) print(ring in inventory2) print(len(inventory2)) for item in inventory2: print(item.description)

1 Answer

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 50,936 Points

According to this stack overflow a suggestion is to read the documentation for functools.total_ordering and add a total order. I added this to your code in a workspace if you or someone wants to check however I add the ring before the dagger to test and sort by name.