473,494 Members | 2,266 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

__cmp__ method

JH
Hi

Can anyone explain to me why the following codes do not work? I want to
try out using __cmp__ method to change the sorting order. I subclass
the str and override the __cmp__ method so the strings can be sorted by
the lengh. I expect the shortest string should be in the front. Thanks
class myStr(str): def __init__(self, s):
str.__init__(self, s) # Ensure super class is initialized
def __cmp__(self, other):
return cmp(len(self), len(other))
a = myStr('abc')
b = myStr('Personal')
c = myStr('Personal firewall')
sorted([c, b, a]) ['Personal', 'Personal firewall', 'abc']


Jun 14 '06 #1
4 6742
Python documentation says:
__cmp__( self, other)
Called by comparison operations if rich comparison (see above) is not defined.

So it seems you have to redefine rich comparisons __lt__, __gt__,
__eq__ etc as well.

If all you need is change sorting order, why not use appropriate
parameters of sorted() function (cmp=... or key=...)?

Jun 14 '06 #2
This probably isn't exactly what you want, but, unless you wanted to do
something especially with your own string class, I would just pass a
function to the sorted algorithm.

eg:

sorted( [a,b,c], cmp=lambda a,b: cmp(len(a),len(b)) )

gives you the below in the right order...

Never tried doing what you're doing, but something about builtin types,
and there's a UserString module...

Hope that helps a bit anyway,

Jon.

JH wrote:
Hi

Can anyone explain to me why the following codes do not work? I want to
try out using __cmp__ method to change the sorting order. I subclass
the str and override the __cmp__ method so the strings can be sorted by
the lengh. I expect the shortest string should be in the front. Thanks
class myStr(str): def __init__(self, s):
str.__init__(self, s) # Ensure super class is initialized
def __cmp__(self, other):
return cmp(len(self), len(other))
a = myStr('abc')
b = myStr('Personal')
c = myStr('Personal firewall')
sorted([c, b, a]) ['Personal', 'Personal firewall', 'abc']


Jun 14 '06 #3
Jon Clements wrote:
This probably isn't exactly what you want, but, unless you wanted to do
something especially with your own string class, I would just pass a
function to the sorted algorithm.

eg:

sorted( [a,b,c], cmp=lambda a,b: cmp(len(a),len(b)) )

gives you the below in the right order...


Or even better in 2.4 or later:
sorted([a,b,c], key=len)

George

Jun 15 '06 #4
JH wrote:
Hi

Can anyone explain to me why the following codes do not work? I want to
try out using __cmp__ method to change the sorting order. I subclass
the str and override the __cmp__ method so the strings can be sorted by
the lengh. I expect the shortest string should be in the front. Thanks
AFAIK (please a Guru correct me if I'm wrong), __cmp__ is used as a
fallback when other comparison operators ( __lt__ etc) are not implemented :
class MyStr(str): .... def __lt__(self, other):
.... return len(self) < len(other)
.... def __le__(self, other):
.... return len(self) <= len(other)
.... def __gt__(self, other):
.... return len(self) > len(other)
.... def __ge__(self, other):
.... return len(self) >= len(other)
.... items = [MyStr("lolo lala"), MyStr("lolo"), MyStr("alal"), MyStr("a")]
sorted(items) ['a', 'lolo', 'alal', 'lolo lala']
But anyway, all this is a WTF. Just using the correct params for sorted
is enough: items2 = ['lolo lala', 'lolo', 'alal', 'a']
sorted(items2, key=len)
['a', 'lolo', 'alal', 'lolo lala']

class myStr(str):


def __init__(self, s):
str.__init__(self, s) # Ensure super class is initialized


This is useless. If you don't override it, parent's init will be called
anyway.

(snip)

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Jun 15 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
4896
by: Jan-Erik Meyer-Lütgens | last post by:
In the Python Language Reference, I found the following statements about using objects as dictionary keys: 1. "__hash__() should return a 32-bit integer." 2. "The only required property is...
3
2878
by: Lee Harr | last post by:
Let's say I have a class class A: def __init__(self, level): self.level = level and I want to put some of these in a list and sort the list by level a1 = A(1)
31
3866
by: John Roth | last post by:
I'm adding a thread for comments on Gerrit Holl's pre-pep, which can be found here: http://tinyurl.com/2578q Frankly, I like the idea. It's about time that all of the file and directory stuff...
3
1453
by: Victor Safronovich | last post by:
please comment this Python 2.2.3 (#42, May 30 2003, 18:12:08) on win32 >>> class A: def __cmp__(self, other): print '%s|%s' %(`self`, `other`) return cmp(self, other) >>> a = A() >>>...
1
2252
by: Erik Max Francis | last post by:
I've come across a limitation in unpickling certain types of complex data structures which involve instances that override __hash__, and was wondering if it was known (basic searches didn't seem to...
39
2762
by: Antoon Pardon | last post by:
I was wondering how people would feel if the cmp function and the __cmp__ method would be a bit more generalised. The problem now is that the cmp protocol has no way to indicate two objects are...
8
1663
by: insyte | last post by:
I have a class that has, as an attribute, an instance of datetime.datetime(). I would like to be able to compare my class directly to instances of datetime.datetime in addition to other instances...
4
1181
by: Thomas Nelson | last post by:
My code: class Policy(list): def __cmp__(self,other): return cmp(self.fitness,other.fitness) j = Policy() j.fitness = 3 k = Policy() k.fitness = 1
17
2690
by: Johannes Bauer | last post by:
Hello group, I'm porting some code of mine to Python 3. One class has the __cmp__ operator overloaded, but comparison doesn't seem to work anymore with that: Traceback (most recent call last):...
0
6989
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7157
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7195
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
7367
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4889
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4579
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3088
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1400
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
644
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.