Есть небольшая задачка. вот код:
class Tag:
def __init__(self, tag, is_single=False):
self.tag = tag
self.text = ""
self.attributes = {}
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
attrs = []
for attribute, value in self.attributes.items():
attrs.append('%s="%s"' % (attribute, value))
attrs = " ".join(attrs)
if self.is_single:
print("<{tag} {attrs}/>".format(tag=self.tag, attrs=attrs))
else:
print(
"<{tag} {attrs}>{text}</{tag}>".format(
tag=self.tag, attrs=attrs, text=self.text
)
)
def __str__(self):
attrs = []
for attribute, value in self.attributes.items():
attrs.append('%s="%s"' % (attribute, value))
attrs = " ".join(attrs)
return "<{tag} {attrs}>{text}</{tag}>".format(tag=self.tag, attrs=attrs, text=self.text)
class HTML(Tag, TopLevelTag):
class TopLevelTag:
def __init__(self, tag, toplevel=False, is_single=False):
self.tag = tag
self.text = ""
self.attributes = {}
self.toplevel = toplevel
self.is_single = is_single
self.children = []
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
if self.toplevel:
print("<%s>" % self.tag)
for child in self.children:
print(child)
print("</%s>" % self.tag)
def __str__(self):
attrs = []
for attribute, value in self.attributes.items():
attrs.append('%s="%s"' % (attribute, value))
attrs = " ".join(attrs)
if self.children:
opening = "<{tag} {attrs}>".format(tag=self.tag, attrs=attrs)
internal = "%s" % self.text
for child in self.children:
internal += str(child)
ending = "</%s>" % self.tag
return opening + internal + ending
else:
if self.is_single:
return "<{tag} {attrs}/>".format(tag=self.tag, attrs=attrs)
else:
return "<{tag} {attrs}>{text}</{tag}>".format(tag=self.tag, attrs=attrs, text=self.text)
if __name__ == "__main__":
with HTML(output="index.html") as doc:
with TopLevelTag("head") as head:
with Tag("title") as title:
title.text = "hello"
head += title
doc += head
with TopLevelTag("body") as body:
with Tag("h1", klass=("main-text",)) as h1:
h1.text = "Test"
body += h1
with Tag("div", klass=("container", "container-fluid"), id="lead") as div:
with Tag("p") as paragraph:
paragraph.text = "another test"
div += paragraph
with Tag("img", is_single=True, src="/icon.png") as img:
div += img
body += div
doc += body
должно получиться что-то вроде:
<html>
<head>
<title>hello</title>
</head>
<body>
<h1 class="main-text">Test</h1>
<div class="container container-fluid" id="lead">
<p>another test</p>
<img src="/icon.png" data-image="responsive"/>
</div>
</body>
</html>
часть я уже написал, но ещё не известно правильно или нет, т.к. немогу оформить сохранение файла в html в классе HTML... ПАМАГИТЕ...
__init__
добавить параметр file и передавать его потом во все print