1+ class Tag (object ):
2+
3+ def __init__ (self , name , contents ):
4+ self .start_tag = '<{}>' .format (name )
5+ self .end_tag = '</{}>' .format (name )
6+ self .contents = contents
7+
8+ def __str__ (self ):
9+ return f"{ self .start_tag } { self .contents } { self .end_tag } "
10+
11+ def display (self , file = None ):
12+ print (self , file = file )
13+
14+
15+ class DocType (Tag ):
16+
17+ def __init__ (self ):
18+ super ().__init__ ('!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" http://www.w3.org/TR/html4/strict.dtd' , '' )
19+ self .end_tag = '' # DOCTYPE doesn't have an end tag
20+
21+
22+ class Head (Tag ):
23+
24+ def __init__ (self , title = None ):
25+ super ().__init__ ('head' , '' )
26+ if title :
27+ self ._title_tag = Tag ('title' , title )
28+ self .content = str (self ._title_tag )
29+
30+
31+ class Body (Tag ):
32+
33+ def __init__ (self ):
34+ super ().__init__ ('body' , '' )
35+ self ._body_contents = []
36+
37+ def add_tag (self , name , contents ):
38+ new_tag = Tag (name , contents )
39+ self ._body_contents .append (new_tag )
40+
41+ def display (self , file = None ):
42+ for tag in self ._body_contents :
43+ self .contents += str (tag )
44+
45+ super ().display (file = file )
46+
47+
48+ class HtmlDoc (object ):
49+
50+ # def __init__(self, title=None):
51+ # self._doc_type = DocType()
52+ # self._head = Head(title)
53+ # self._body = Body()
54+
55+ def __init__ (self , doc_type , head , body ):
56+ self ._doc_type = doc_type
57+ self ._head = head
58+ self ._body = body
59+
60+ def add_tag (self , name , contents ):
61+ self ._body .add_tag (name , contents )
62+
63+ def display (self , file = None ):
64+ self ._doc_type .display (file = file )
65+ print ('<html>' , file = file )
66+ self ._head .display (file = file )
67+ self ._body .display (file = file )
68+ print ('</html>' , file = file )
69+
70+
71+ if __name__ == '__main__' :
72+ # my_page = HtmlDoc('Demo HTML Doc')
73+ # my_page.add_tag('h1', 'Main heading')
74+ # my_page.add_tag('h2', 'sub-heading')
75+ # my_page.add_tag('p', 'This is a paragraph that will appear on the page')
76+ #
77+ # with open('test.html', 'w') as test_doc:
78+ # my_page.display(file=test_doc)
79+
80+ new_body = Body ()
81+ new_body .add_tag ('h1' , 'Aggregation' )
82+ new_body .add_tag ('p' , "Unlike <strong>composition</strong>, aggregation uses existing instances"
83+ " of objects to build up another object." )
84+ new_body .add_tag ('p' , "The composed object doesn't actually own the objects that it's composed of"
85+ " - if it's destroyed, those objects continue to exist." )
86+
87+ new_docType = DocType ()
88+ new_header = Head ('Aggregation document' )
89+ my_page = HtmlDoc (new_docType , new_header , new_body )
90+
91+ with open ('test3.html' , 'w' ) as test_doc :
92+ my_page .display (file = test_doc )
0 commit comments