Newbie-Can I loop thru all class variables?

Kragen Sitaker kragen at dnaco.net
Sun Oct 1 23:42:02 EDT 2000


In article <6vQB5.58$QI1.115495 at news.pacbell.net>,
Eric <ewalstad at yahoo.com> wrote:
>To summarize: Can I loop thru all the variables in a class without needing
>to know the names of the variables?

Yes, dir(class) gives you the list of class variables, but that's not
what you ask below.

>I'm trying to do something like pickling, but I want to send the class
>variables to an output string formatted in XML fashion.

When you do this, how will you turn the output string back into an
object?  AFAIK there's no equivalent of Perl's 'bless'.

>And let's say I have a "CUser" class . . .
>So that if I make a call like:
>        user.toXML()    # 'user' is of type CUser
>
>The result is a string that looks like:
><User>
>  <Name>Jane Doe</Name>
>  <Company>Widgets R Us</Company>
>  ...etc...
>  <Phone>1234567890</Phone>
></User>
>
>So, how do I loop thru 'user''s variables to generate the output string?

It sounds like you want user's variables, which are the attributes of
an instance (or instance variables, or data members), not CUser's
variables, which are the class variables.

Instance variables are in user.__dict__; I think user.__dict__.keys()
is what you want.

HTH.
-- 
<kragen at pobox.com>       Kragen Sitaker     <http://www.pobox.com/~kragen/>
Perilous to all of us are the devices of an art deeper than we ourselves
possess.
                -- Gandalf the Grey [J.R.R. Tolkien, "Lord of the Rings"]





More information about the Python-list mailing list