I'm working on a Python module that can output HTML code. When I attempt to make child elements and try to add an attribute (such as an id or style), it would add the attributes to the parent and all other children; however I changed a few things in the class and it fixed it and it has me puzzled on how it works. The original class __init__ looked like so:
ezhtml.py (class Element)
def __init__(self, tag_: str, attr=dict(), text=str()):
'''
tag_ : the HTML tag for the element
attr : a dictionary containing any attributes required for the element (can be added later)
text : the innerText for the HTML element
'''
self.__tag = tag_
self.__Attributes = attr
self.__children = {}
self.__text_order = True
self.__text = text
for key in self.__Attributes.keys():
setattr(self, key, self.__Attributes[key])
And the code to make a simple site looks like this:
sample.py
from ezhtml import *
html = Element("html")
head = Element('head')
html.appendChild(head)
html.head.appendChild(Element('title', text='Title To My Webpage'))
html.appendChild(Element('body'))
html.body.appendChild(Element('h1'))
html.body.h1.add_attr('style', 'background-color: black; color: white; text-align: center;')
html.body.h1.text = "Hello world"
print(html)
And the desired output is the following:
<html>
<head>
<title>Title To My Webpage</title>
</head>
<body>
<h1 style="background-color: black; color: white; text-align: center;">Hello world</h1>
</body>
</html>
Yet the output I get is this:
<html style="background-color: black; color: white; text-align: center;">
<head style="background-color: black; color: white; text-align: center;">
<title style="background-color: black; color: white; text-align: center;">Title To My Webpage</title>
</head>
<body style="background-color: black; color: white; text-align: center;">
<h1 style="background-color: black; color: white; text-align: center;">Hello world</h1>
</body>
</html>
Then I messed around and changed the __init__ method to the following:
def __init__(self, tag_: str, attr=None, text=str()):
'''
tag_ : the HTML tag for the element
attr : a dictionary containing any attributes required for the element (can be added later)
text : the innerText for the HTML element
'''
self.__tag = tag_
if attr is None:
self.__Attributes = dict()
else:
self.__Attributes = attr
self.__children = {}
self.__text_order = True
self.__text = text
for key in self.__Attributes.keys():
setattr(self, key, self.__Attributes[key])
And that gave me the desired output. I don't see how that should change anything, but it worked and gave me the result I wanted. I'm just curious how or why this works.