0

Is there a way to list through subclass value? I'd like 'by' variable to be the first one and sort entire list by .number subclass.

class Abcd:
    def __init__(self, name, number):
        self.name = name
        self.number = number

ax = Abcd("a", 20)
by = Abcd("b", 1)

lst = [ax, by]

print lst[0]
list.sort(lst)
print lst[0]
Gunnm
  • 974
  • 3
  • 10
  • 21

1 Answers1

1

This should do. All I am doing is adding a key to the sort function and some stuff to make printing look better but those really aren't necessary.

class Abcd:
    def __init__(self, name, number):
        self.name = name
        self.number = number

    def __str__(self):
        return "{} and {}".format(self.name, self.number)

    def __repr__(self):
        return self.__str__()

ax = Abcd("a", 20)
by = Abcd("b", 1)

lst = [ax, by]

print str(lst)
list.sort(lst, key=lambda x: x.number)
print str(lst)
Jared Mackey
  • 3,998
  • 4
  • 31
  • 50