How would I sort a list of classes in Python, making sure that any child class is before any of its parent classes in the list?
I ask because I want to see what type out of a list of types, an object belongs to, but find the most specific type, if it belongs to multiple.
Attrgetter Function There is still yet another way we can sort objects of a class in Python. Another way we can do is through the use of the attrgetter() function in Python. This function can get the attribute of an object so that the sorted() function can sort the objects of the class.
Yes, you can do multiple inheritance. please note the order of class in ExampleSimMod matters.
When we search for an attribute in a class that is involved in python multiple inheritance, an order is followed. First, it is searched in the current class. If not found, the search moves to parent classes. This is left-to-right, depth-first.
Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted list from an iterable.
Simply sort by len(cls.mro())
.
If C2
is a subclass of C1
, it must hold that len(C1.mro()) < len(C2.mro())
(because each class in C1.mro()
must also appear in C2.mro()
). Therefore, you can simply sort by the length of the mro list:
class A(object): pass
class X(object): pass
class B(A, X): pass
class C(B): pass
class D(C): pass
sorted([B, C, A, D, X], key = lambda cls: len(cls.mro()))
=> [__main__.A, __main__.X, __main__.B, __main__.C, __main__.D]
To also support old-style classes, you can replace cls.mro()
with inspect.getmro(cls)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With