Getting back an Object

Gary Herron gherron at islandtraining.com
Fri Mar 28 01:29:13 EDT 2008


David Anderson wrote:
> Well, I've got a little problem, I have a list that contains objects 
> from the class C, then I use those objects.__str__ to generate a 
> ListCtrl, A wxPython widget that makes a list of strings and then you 
> can handle events when selected, and returns the string selcted, how 
> can I access the "parent" of that string?
> I tried to search on the array like this:
> def search(self, string):
>       for obj in self.list:
>            if string == obj.__str__:
>                  return obj
>        return None
>
> But I always get None... What am I doing wrong?

Once again, you are confused over the difference between a value and a 
function that, when called,  returns a value.

obj.__str__ is a function. 

If you call it like this, obj.__str__(), then you get a string.

So your comparison should be 
      if string == obj.__str__():

Slightly better would be to call
    str(obj)
and let Python translate that into a call to __str__.


But even better is to replace this rather bogus approach with something 
better.  When you create an object, record its string representation in 
a dictionary to be used to recover the object when given a string later:

That is, for each object obj do:
    objMap[str(obj)] = obj

and later with the string in hand, do
  obj = objMap[string]

One other word of warning.  It is best to not use a variable named 
"string" as Python has a builtin type of that name which would become 
inaccessible if you redefine.

Gary Herron




More information about the Python-list mailing list