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']
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=...)?
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']
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
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('@')])" This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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)
|
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...
|
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()
>>>...
|
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...
| |
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...
|
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...
|
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
|
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):...
|
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...
|
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,...
| |
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...
|
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...
|
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...
|
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...
|
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...
|
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 ...
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |