Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdaniel steinberg
14,651 PointsSorted 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
54,971 PointsAccording 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.
daniel steinberg
14,651 Pointsdaniel steinberg
14,651 Pointsty!