Order of constructor/destructor invocation

Jeremy Bowers newsfroups at jerf.org
Tue Mar 5 01:34:13 EST 2002


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