Jump to content
  • Advertisement
Sign in to follow this  
Daniel Miller

easy cheesy python question

This topic is 4877 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I need to make a collection of class-instances sortable. So, I checked the docs, and found a page on how to mimic being a numeric type: http://docs.python.org/ref/numeric-types.html However, it doesn't have anything about comparison operators. How do I do this?

Share this post


Link to post
Share on other sites
Advertisement
http://python.active-venture.com/ref/customization.html

Overload the below 'rich comparison' operators

__lt__( self, other)


__le__( self, other)


__eq__( self, other)


__ne__( self, other)


__gt__( self, other)


__ge__( self, other)

New in version 2.1. These are the so-called ``rich comparison'' methods, and are called for comparison operators in preference to __cmp__() below. The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y and x<>y call x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y). These methods can return any value, but if the comparison operator is used in a Boolean context, the return value should be interpretable as a Boolean value, else a TypeError will be raised. By convention, False is used for false and True for true.

Share this post


Link to post
Share on other sites
Quote:
Original post by Daniel Miller
Thank you! :)

I can't beleive I missed that!


Actually, they are tricky to find. Make use of the dir() function - dir(object) returns a list of all valid methods for that object, and you can usually find a list of magic functions there.


Example:

IDLE 1.0.3
>>> a = 5
>>> dir(a)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!