Simple questions on use of objects (probably faq)

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Mar 9 23:02:02 CET 2006


On Thu, 09 Mar 2006 13:23:22 +0100, Brian Elmegaard wrote:

> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
> 
>> Can you explain more carefully what you are trying to do? If you want the
>> square of the maximum value, just do this:
> 
> I want to get the value of another attribute of the instance with
> maximum x. 

One solution to that has already been given, using the DSU
(decorate-sort-undecorate) idiom:

list_of_instances = [C(x) for x in (1, 2, 3, 4)]
data = [(instance.x, instance.y) for instance in list_of_instances]
m = max(data)
print m[1]  # prints the y value of the instance with the largest x value


But perhaps a better way would be to define a __cmp__ method for your
class so that comparisons are done by comparing the x attribute:


class C:
    def __init__(self, x):
        self.x = x
        self.y = something_else()
    def __cmp__(self, other):
        # not tested
        try:
            if self.x < other.x:
                return -1
            elif self.x > other.x:
                return +1
            else:
                return 0
        except:
            return NotImplemented


With this method in the class, your solution is easier than ever:

data = [C(x) for x in (1,2,3,4)]
m = max(data)
print m.x
print m.y



-- 
Steven.




More information about the Python-list mailing list