Simple questions on use of objects (probably faq)

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Mar 9 06:57:03 EST 2006


On Thu, 09 Mar 2006 12:24:05 +0100, Brian Elmegaard wrote:

> James Stroud <jstroud at ucla.edu> writes:
> 
>> You should look into __cmp__ and other magic methods. This is probably
>> the type of functionality you seem to be after.
> 
> Good example, I need to look at the magic methods.
> What I want is to get the value of another variable in C. Would I need to
> use __repr__ and get the id from it to find xx of the instance with
> maximum x? 
> 
> class C:
>    def __init__(self, x):
>      self.x = x
>      self.xx = x*x
> 
> sees = [C(x) for x in (4,7,1,3,0,9,2)]  # random-ish ints
> print max(sees)


Can you explain more carefully what you are trying to do? If you want the
square of the maximum value, just do this:

max(4,7,1,3,0,9,2)**2


__repr__ is *not* the way to get the ID of a general object:

>>> repr(4)
'4'

For some objects, the default representation includes the ID as part of
the representation string, but that's not the way to get the ID. The way
to do that is with the id() function.

Right, now that you've learnt how to get the ID of an object, scrub it
from your mind. You won't need it. You can't use it. It isn't the way to
do whatever you are trying to do, whatever it is that you are trying to
do. These aren't the droids you are looking for.

[The above paragraph is always true, except for the exceptions when it is
not true. You will know when you need id(). If you only *think* you need
id(), you don't need it.]

Seriously though, you can't generally work backwards to see where an
object came from (which list, which dictionary, whatever). In general,
objects do not know what references there are to that object. If your
algorithm relies on object X knowing that it is the 5th item of list L,
then you must either store that information yourself somewhere, and
maintain it, or you must change your algorithm. 



-- 
Steven.




More information about the Python-list mailing list