simple question about classes

Scott Hathaway slhath at home.com
Mon Aug 13 21:34:43 EDT 2001


You guys are awesome!  That is what I needed.

Thanks,
Scott

"Alex Martelli" <aleaxit at yahoo.com> wrote in message
news:9l9gn102ufh at enews4.newsguy.com...
> "Scott Hathaway" <scott_hathaway at riskvision.com> wrote in message
> news:3b783669.0 at 216.0.152.7...
> > If I have a class, is there a way to iterate through the name of all of
> the
> > 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
> further:
>             for varname in a.__dict__.keys():
>                 if varname.startswith('_'): continue
>                 value = getattr(a, varname)
>                 if not callable(value):
>                     print varname, value
>
>
> Alex
>
>
>





More information about the Python-list mailing list