compare classes and not class instances

J

jantod

I not only want to compare class *instances* but also the classes
themselves. Something like:

class T(object):
@classmethod
def __cmp__(cls, other):
return cmp(cls.__name__, other.__name__)
@instancemethod
def __cmp__(self, other):
return cmp(self.x, other.x)

class B(T): pass
class A(T): pass

sorted([B, A]) => [A, B]

My motivation for doing so is simply to sort classes based on their
names and not (as it seems is the default behaviour) on the order in
which they were created.

I guess I could always just do something like sorted(classes,
key=lambda cls: cls.__name__)...but where's the fun in that? :)
 
P

Peter Otten

I not only want to compare class *instances* but also the classes
themselves. Something like:
sorted([B, A]) => [A, B]

My motivation for doing so is simply to sort classes based on their
names and not (as it seems is the default behaviour) on the order in
which they were created.

I guess I could always just do something like sorted(classes,
key=lambda cls: cls.__name__)...but where's the fun in that? :)

A class is just an instance of its metaclass. Therefore the metaclass is the
right place to implement the __cmp__() method:
.... class __metaclass__(type):
.... def __cmp__(cls, other):
.... return cmp(cls.__name__, other.__name__)
....
class B(T): pass ....
class A(T): pass ....
class C(T): pass ....
sorted([C, B, A])
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>]

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top