所以我目前正在用 Python 構建一個 Html 渲染程式,它使用兩個基類:
- SingleTag - 用于沒有任何子標簽的標簽,例如
標簽
- ContainingTag - 對于具有嵌套標簽的標簽,例如 Html 標簽、Div 標簽等...
這是包含這些類以及從它們繼承的子類的檔案:
class ContainingTag:
def __init__(self, children):
self.open_tag = "<" self.__class__.__name__.lower() ">"
self.close_tag = "</" self.__class__.__name__.lower() ">"
self.children = children
def render(self):
print("\t" self.open_tag)
for child in self.children:
print("\t \t" str(child.render()))
print("\t" self.close_tag)
class SingleTag:
"""A class to represent an html tag"""
# Class initialiser
def __init__(self, inner_html):
self.open_tag = "<" self.__class__.__name__.lower() ">"
self.close_tag = "</" self.__class__.__name__.lower() ">"
self.inner_html = inner_html
# Prints html
def render(self):
return self.open_tag self.inner_html self.close_tag
class Html(ContainingTag):
def __init__(self, children):
super().__init__(children)
self.open_tag = "<!DOCTYPE html>\n" "<" self.__class__.__name__.lower() ">"
def render(self):
print(self.open_tag)
for child in self.children:
print("\t \t" str(child.render()))
print(self.close_tag)
class Head(ContainingTag):
def __init__(self, children):
super().__init__(children)
class Style(ContainingTag):
def __init__(self, children):
super().__init__(children)
class Body(ContainingTag):
def __init__(self, children):
super().__init__(children)
class Div(ContainingTag):
def __init__(self, children):
super().__init__(children)
class P(SingleTag):
def __init__(self, inner_html=None):
super().__init__(inner_html=None)
self.inner_html = inner_html
在 SingleTag 物件上使用 render 方法時,它會按預期呈現,但在 ContainingTag 上使用 render 方法時,它會在每個結束標記后列印“None”,如下所示:
<Opening ContainingTag>
<Closing ContainingTag>
None
有人可以解釋為什么這會一直列印以及如何解決這個問題嗎?謝謝。
uj5u.com熱心網友回復:
錯誤似乎是該render函式實際上沒有回傳任何內容,因此回傳了默認值 ie None。
def render(self):
print(self.open_tag)
for child in self.children:
print("\t \t" str(child.render()))
print(self.close_tag)
# Add a return statement
uj5u.com熱心網友回復:
更簡單的方法:
- 覆寫內置
__str__()方法而不是創建render - 將標簽名稱作為引數傳遞給類構造器,因此您不需要創建很多子類(您可能還想創建
HTML子類)
class ContainingTag:
def __init__(self, name, children):
self.name = name
self.children = children
def __str__(self):
return f'<{self.name}>\n' ''.join([str(c) for c in self.children]) f'</{self.name}>\n'
class SimpleTag:
def __init__(self, name, html):
self.name = name
self.html = html
def __str__(self):
return f'<{self.name}>{self.html}</{self.name}>\n'
p1=SimpleTag('P', 'Hello')
p2=SimpleTag('P', 'World')
d=ContainingTag('DIV', [p1,p2])
b=ContainingTag('BODY', [d])
print(str(p1))
<P>Hello</P>
print(str(b))
<BODY>
<DIV>
<P>Hello</P>
<P>World</P>
</DIV>
</BODY>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463348.html
