'Python sorting a list of classes based on static property
I have some problem that I have yet to find how to solve. I have an array of classes (not instances) that I need to sort based on some static field.
class Base2:
pass
class C1(Base2):
order_id = 1
class C3(Base2):
order_id = 3
class C2(Base2):
order_id = 2
import operator
subclasses_list = Base2.__subclasses__()
print(subclasses_list)
for c in subclasses_list:
print(c.order_id)
subclasses_list_sorted = subclasses_list.sort(key=lambda x: x.order_id) # operator.attrgetter("order_id")
print(subclasses_list_sorted)
The output looks like this.
[<class '__main__.C1'>, <class '__main__.C3'>, <class '__main__.C2'>]
1
3
2
None
So, the order_id is seen when iterating over the elements in the list as the print statements show.
But, my main mystery is why the sort method returns a None. It can't deal with extracting the static field?
Any ideas? Much appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
