Newbie question on Classes

John Machin sjmachin at
Fri Jan 11 22:07:55 CET 2008

On Jan 11, 9:27 am, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
> > -----Original Message-----
> > From: python-list-bounces+jr9445=att.... at [mailto:python-
> > list-bounces+jr9445=att.... at] On Behalf Of Adrian Wood
> > Sent: Thursday, January 10, 2008 4:47 PM
> > To: python-l... at
> > Subject: Newbie question on Classes
> > I can call man.state() and then woman.state() or Person.state(man) and
> > Person.state(woman) to print the status of each. This takes time and
> > space however, and becomes unmanageable if we start talking about a
> > large number of objects, and unworkable if there is an unknown number.
> > What I'm after is a way to call the status of every instance of Man,
> > without knowing their exact names or number.
> How about searching the garbage collector?

Not a good idea, because gc is an implementation artifact and in fact
is specific to the C Python implementation; you won't find it in e.g.
Iron Python or Jython.

Not a good idea, because you are replacing iterating over a collection
of all the objects of interest (and *only* those of interest) with a
clumsy [see below] rummage through a potentially far much larger
collection of objects.

> import gc
> from random import random
> class Person:
>     def __init__(self):
> random() * 1000 + 1
>     def WhoAmI(self):
>         return
> a = Person()
> b = Person()
> for i in gc.get_objects():
>     try:
>         # classes have __class__ and __dict__ defined according to the
> docs

Again, implementation artifacts.

>         if i.__class__ and i.__dict__ :

In general, i.__dict_ could be empty. You probably mean

>             print i.__class__
>             if str(i.__class__) == '__main__.Person':

and what if the class is not defined in __main__ but in some other

Have you considered
    i.__class__ is Person
or the usual (and underscore-free) idiom
    isinstance(i, Person) ?

>                 print "\tI am", i.WhoAmI()
>     except:
>         pass

Blindly ignoring all possible exceptions is A Very Bad Idea.

More information about the Python-list mailing list