Getting aquainted with the concepts of Object Oriented Programming by developing a writer class.
HTML files have a relatively simple structure. Here is an example:
<!DOCTYPE html>
<html>
<body>
<h1>A large title</h1>
<h2>A smaller title</h2>
<p>
A paragraph with more or less text. Rather less.
</p>
<img alt="Image not found" src="/path/to/some/image.png">
<h2>Another smaller title</h2>
<p>
Another paragraph with more or less text. It depends on your mood.
</p>
</body>
</html>
Your task is to write an HTMLFile
class, which will help you to write such files in python. At instantiation, the HTMLFile
class must accept a path to a file which will be created or overwritten by the object. The path must be ending with .html
, otherwise the __init__
method should raise an error. The class must define the following instance methods:
add_title
, which adds a title to the file. The size of the title must be specified with a keyword argument.add_paragraph
, which add a paragraph to the file.add_image
, which adds an image command to the file.end_file
, which writes the closing lines of the file.display_html
, which opens the file in your browser.The class should define a new property, n_lines
, which returns the number of lines of the html file.
For example, the following code should write the template above and print the total number of lines:
file = HTMLFile('my_template.html')
file.add_title('A large title')
file.add_title('A smaller title', small=True)
file.add_paragraph('A paragraph with more or less text. Rather less.')
file.add_image('/path/to/some/image.png', alt='Image not found')
file.add_title('Another smaller title', small=True)
file.add_paragraph('Another paragraph with more or less text. It depends on your mood.')
file.end_file()
print(file.n_lines)
Tips: for now, I suggest to open and close the text file at each function call (ideally by using the with
syntax). Next week I might show you how to do it in a more elegant way.
markdown is a lightweight mark-up language which is widely used to write simplified files which are then converted to HTML with an external tool (in fact, this is exactly what the Jupyter Notebook is doing). The HTML template above can be simplified in markdown to:
# A large title
## A smaller title
A paragraph with more or less text. Rather less.
![Image not found](/path/to/some/image.png)
## Another smaller title
Another paragraph with more or less text. It depends on your mood.
Write a MarkdownFile
which works much like the HTMLFile
class. Both classes must inherit from a FileWriter
class, which must take care of the file handling logic common to both classes.
Back to the table of contents