Yes. Not providing an __init__ just means it uses the init of the
superclass, list. That’s fine. All you’re doing is making a subclass
with one extra method - everything else comes from the superclass.
Thank you very much, Cameron and Steven. I was wondering if it’s possible to write merge sort by class method rather than a function? Is it appropriate to do so? Any comments on the code are welcome.
# merge function for mergesort
def merge_sorted(x, y): # assume that the two sequences are sorted
res = 
while x and y:
if x <= y:
res += [x]
res += [y]
return res + x
return res + y
def mergesort(x): # assume that x is an non-empty list
n = len(x)
if n == 1:
elif n == 2:
return [min(x), max(x)]
else: # n == 3 or n ==4:
first_half = x[: n//2]
second_half = x[n//2:]
first_half_sorted = mergesort(first_half)
second_half_sorted = mergesort(second_half)
return merge_sorted(first_half_sorted, second_half_sorted)
import numpy as np
listx = list(np.random.permutation(10))
Well, you can definitely do it with a subclass as in your own previous
The difficulty with a class method (no, not a “@classmethod” class
method, I mean an “instance method” - you mean this also) is getting it
into the class you want it to work on.
The subclass approach means you need to work against instances of the
subclass. Using your MyList as an example, that works fine, but breaks
as soon as regular lists get mixed in, as they lack the method. You end
up needing to have convenient factories to convert ordinary lists into
the subclass in order to use the method. That quite possibly involves
copying the list (which is expensive) and also directly breaks the “sort
in place” aspect of your example. And it also becomes wordy and
cumbersome very quickly.
You can define a “mixin” class (a bare class with just the extra
methods) and include it in any subclasses:
... in place merge sort ...
and easily mix that into any subclasses:
class MyList(list, SortableMixin):
... special "sparse" list implementation of a list ...
but you’re still subclassing. I do not know if you can modify a class’s
method resolution order (the __mro__ attribute). [… experiments…]
No you cannot.
Anyway, the advantage of a function is that you can apply it to any
type of object (provided the object is suitable). So your mergesort
function can be applied to a list or the a MyList or any other
collection which looks enough like a list.
So a function can often be a good way to do things, particularly since
it isn’t bound to a specific class.