Newbie - Recursive calls in class objects...

Tom nospam at nospam.com
Tue Oct 3 10:37:47 EDT 2000


"Eric" <ewalstad at yahoo.com> wrote in message
news:ST9C5.97$Q13.124792 at news.pacbell.net...
> Hi all,
>
> To summarize: How do I test if a "__dict__" item is a class object or an
> instance variable?
>
> I am trying to do something like pickling where I recursively call an
> object's method that prints out the object's instance variables.  I am
> looping thru the object's instance variables, printing each one.  I do
this
> with the line:
> for t in self.__dict__.items():  (See listing below)

As an aside, did you know that you can write this line as:
    for tkey, tvalue in self.__dict__.items()

> I get into trouble if one of the instance variables ( t[0] )  is itself an
> object to be printed.  I can't seem to figure out how to test if the
> variable is an object.

Every variable is an object (or, in Python-speak, every name binds to an
object).

> I've tried "isinstance(t[0], CElement)" which didn't work.
> I've tried "issubclass(t[0], CElement)" which didn't work, either.

I think you mean "isinstance(t[1], CElement)", because t[0] is the key,
whereas t[1] is the value.

Tom.

> Thanks for your help!
> Eric.
>
>
> Here are my classes:
>
> class CElement:
>     """Base Class for elements in a project"""
>     pad = "  "
>     def __init__(self):
>         self.Name = ""
>         self.Type = ""
>         self.PadMult = 1                # equals the number of parent
nodes
> this object will have in the XML structure
>         self.XmlTag = self.Type     # the node text used to mark the XML
> node (i.e., 'User' => <User></User>)
>
>     def toXML(self):
>         strXML=""
>         strXML = self.pad * self.PadMult + "<" + self.XmlTag + ">\n"
>         for t in self.__dict__.items():
> ******     NEED HELP HERE   ******
>             strXML = strXML + self.pad * (self.PadMult + 1) + "<" + t[0] +
> ">" + t[1] + "</" + t[0] + ">\n"
>             strXML=strXML + self.pad * self.PadMult + "</" + self.XmlTag +
> ">\n"
>         print strXML
>
> class CUser(CElement):
>     """Defines Users"""
>     def __init__(self):
>         CElement.__init__(self)
>         self.Name = "New User"
>         self.Type = "User"
>         self.Address = ""
>         self.City = ""
>         self.State = "CA"
>         self.Zip = ""
>         self.PadMult = 1
>
> class CProject(CElement):
>     """Defines a project"""
>     def __init__(self):
>         CElement.__init__(self)
>         self.Name = "New Project"
>         self.Type = "Project"
>         self.XmlTag = self.Type
>         self.User = CUser()
>         self.PadMult = 1
>
>
>





More information about the Python-list mailing list