simple question about classes

Alex Martelli aleaxit at
Mon Aug 13 23:23:10 CEST 2001

"Scott Hathaway" <scott_hathaway at> wrote in message
news:3b783669.0 at
> If I have a class, is there a way to iterate through the name of all of
> properties (public variables) of the class which would include public vars
> that were added at the time of instantiation?

Yes, of course -- but your example show that you want to
iterate on the attributes of an *instance*, not really those
of the *class* itself.

> class a():

Wrong syntax (empty parentheses forbidden here, sigh).

>     getPublicVars(self):
>         # loop here that prints each variable and it's value
            for varname in a.__dict__.keys():
                print varname, getattr(a,varname)

This gives only the attributes of the instance -- no check on whether
they're callable (methods rather than properties) and no check on
further attributes that belong to the class or its bases.  It's easy
to restrict the list by forbidding callables:
            for varname in a.__dict__.keys():
                value = getattr(a, varname)
                if not callable(value):
                    print varname, value
and it's not too hard to similarly check self.__class__ and
(recursively upwards) its __bases__ while avoiding duplicates,
but it starts to get hairy -- maybe dir() in 2.2 will do that for
you (Tim and Guido were mooting that as a possibility, and
clearly it WOULD be handy here).

You do specify ''public'' properties so you may want to filter
            for varname in a.__dict__.keys():
                if varname.startswith('_'): continue
                value = getattr(a, varname)
                if not callable(value):
                    print varname, value


More information about the Python-list mailing list