Skip to content

Instantly share code, notes, and snippets.

@tirinox
Created March 9, 2019 07:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tirinox/7fb5606c99dc6e6f878d10619661f5b2 to your computer and use it in GitHub Desktop.
Save tirinox/7fb5606c99dc6e6f878d10619661f5b2 to your computer and use it in GitHub Desktop.
import operator
class Item:
def __init__(self, name, price, qty):
self.name = name
self.price = price
self.qty = qty
def total_cost(self):
return self.price * self.qty
def __repr__(self):
return f'({self.name} ${self.price} x {self.qty} = ${self.total_cost()})'
items = [
Item("iPhone", 999, 5),
Item("iMac", 2999, 2),
Item("iPad", 599, 11)
]
def print_items(title, item_list):
print(title)
print(*item_list, sep=', ', end='\n\n')
print_items('Original:', items)
items_by_price = sorted(items, key=operator.attrgetter('price'))
print_items('Sorted by price:', items_by_price)
items_by_total_cost = sorted(items, key=operator.methodcaller('total_cost'))
print_items('Sorted by total cost:', items_by_total_cost)
"""
Original:
(iPhone $999 x 5 = $4995), (iMac $2999 x 2 = $5998), (iPad $599 x 11 = $6589)
Sorted by price:
(iPad $599 x 11 = $6589), (iPhone $999 x 5 = $4995), (iMac $2999 x 2 = $5998)
Sorted by total cost:
(iPhone $999 x 5 = $4995), (iMac $2999 x 2 = $5998), (iPad $599 x 11 = $6589)
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment