Newbie-Can I loop thru all class variables?

Eric ewalstad at yahoo.com
Sun Oct 1 20:17:28 EDT 2000


Hi all,
To summarize: Can I loop thru all the variables in a class without needing
to know the names of the variables?

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

Class CElement:
    "Base Class for elements in a project"
    pad = "  "
    def __init__(self):
        self.Name = ""
        self.Type = ""

    def toXML():
        strXML="<" + self.Type + ">"

        ****I NEED HELP HERE****
        # TODO: Add code to loop thru all the class variables here


        strXML=strXML + "</" + self.Type + ">"
        return strXML

And let's say I have a "CUser" class that inherits from the CElement class:
class CUser(CElement):
     "Defines Users"
     def __init__(self):
      self.Name = ""
      self.Company = ""
      self.Address = ""
      self.City = ""
      self.State = ""
      self.Zip = ""
      self.email = ""
      self.Phone = ""

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?

Thanks very much,

Eric.





More information about the Python-list mailing list