Order of constructor/destructor invocation

Reginald B. Charney news at charneyday.com
Tue Mar 5 12:29:30 EST 2002


In this idiom, I am not trying to traverse a tree. I am trying to execute
what I declare. Also, this idiom allows for very shallow dependencies. There
is no inheritance here. In this example, I am trying to write:

h = HTML(); b = BODY(); p = PHP()

Note that there is no interdependencies. I could also have written (but is
would produce invalid HTML):

b = BODY(); p = PHP(); h = HTML()

However, it is pretty clear what I have written and the order I expect
things to be done. Please compare it with the more classic example you wrote
where the logical ordering needed to be explicitly coded for the right
results to be produced. Using this idiom, here is what my __main__ would
look like:

if __name__ == "__main__":
     print "Start of program"
      h = HTML()
      b = BODY()
      p = PHP()
...

Thanks.

Reg.

"Jeremy Bowers" <newsfroups at jerf.org> wrote in message
news:3C8466F9.2080903 at jerf.org...
> Reginald B. Charney wrote:
>
> > In Python, are destructors defined to be invoked in reverse order of
> > constructors? The following program illustrates the problem:
> >
> > class HTML:
> >     def __init__(self): print "<HTML>"
> >     def __del__(self):  print "</HTML>"
> >
> > class BODY:
> >     def __init__(self): print "<BODY>"
> >     def __del__(self):  print "</BODY>"
> >
> > class PHP:
> >     def __init__(self): print "<?PHP "
> >     def __del__(self):  print "?>"
>
>
> You aren't trying to actually build an HTML document that way, are you?
> Please tell me this is just for the sake of example. The more
> conventional example would be something like
>
> class example:
> def __init__(self): print "example created"
> def __del__ (self): print "examples destroyed"
>
> Destructors are for cleaning up objects, not traversing trees. If you
> really are trying to build HTML documents, learn how to traverse trees
> correctly.
>
>
> ----
> import string
>
> class HTMLTag:
> def __init__(self):
> self.children = []
> def output(self):
> childText = [child.output() for child in self.children]
> return string.join([self.begin] + childText + [self.end])
>
> class HTML(HTMLTag):
> begin = "<HTML>"
> end = "</HTML>"
>
> class BODY(HTMLTag):
> begin = "<BODY>"
> end = "</BODY>"
>
> class PHP(HTMLTag):    # OK, so that's a bit of a semantic stretch...
> begin = "<?PHP "
> end = "?>"
>
> if __name__ == "__main__":
>      print "Start of program"
>      h = HTML()
>      h.children.append(BODY())
>      h.children[0].children.append(PHP())
>      print h.output()
> ----
>
>
> This isn't the One True Implementation of this idea, just a nudge.
>





More information about the Python-list mailing list