finding name of instances created

André andre.roberge at gmail.com
Sun Jan 23 07:40:45 EST 2005


Scott David Daniels wrote:
> André Roberge wrote:
> > Craig Ringer wrote:
> >
> >> On Fri, 2005-01-21 at 16:13 -0800, André wrote:
> >>
> >>> Short version of what I am looking for:
> >>>
> >>> Given a class "public_class" which is instantiated a few times
e.g.
> >>>
> >>> a = public_class()
> >>> b = public_class()
> >>> c = public_class()
> >>>
> >>> I would like to find out the name of the instances so that I
could
> >>> create a list of them e.g.
> >>> ['a', 'b', 'c']
> >
> > ...
> > Behind the scene, I have something like:
> > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
> > and have mapped move() to correspond to robot_dict['robot'].move()
> > (which does lots of stuff behind the scene.)
> > ...[good explanation]...
>  > Does this clarify what I am trying to do and why?
>
> Yup.  Would something like this help?
>
>      parts = globals().copy()
>      parts.update(locals())
>      names = [name for name, value in parts.iteritems()
>               if isinstance(value, Robot)] # actual class name here
>
> Note, however, that
>
>      a = b = CreateRobot()
>
> will give two different names to the same robot.
>
> And even:
>
>      Karl = CreateRobot()
>      Freidrich = CreateRobot()
>      for robot in (Karl, Freidrich):
>          robot.move()
>
> Will have two names for "Freidrich" -- Freidrich and robot
>
> --Scott David Daniels

Thanks for your suggestion.
It might have been interesting to try, but I am going to
try and implement a suggestion given by Nick Coghlan instead.
André




More information about the Python-list mailing list