我有一个 python 文件,其中包含诸如 h1
和 img
以及 strong
之类的函数,用于使用样式文本。每个函数的定义如下:
def _wrapTag(tag, text, **attributes):
out = _createTag(tag, **attributes)
out += text
out += "</" + tag + ">"
return out
def _createTag(tag, **attributes):
out = "<" + tag
if attributes:
for attr, value in attributes:
out += " " + attr + "=\"" + value + "\""
out += ">"
return out
def h2(text, **attributes):
return _wrapTag("h2", text, **attributes)
在理想的情况下,要使用 modal
类创建 div
,我会调用 div(content, class="modal")
但是 class
是受限制的关键字。有没有办法绕过这个问题,而不需要向 _createTag
添加特殊情况?
最佳答案
PEP 8标准处理方法是添加尾随下划线:
- single_trailing_underscore_:按惯例使用以避免与 Python 关键字冲突,例如
Tkinter.Toplevel(master, class_='ClassName')
这是一种常见的解决方法,不会让任何人感到惊讶。您可以在代码中实现它,例如:
def _createTag(tag, **attributes):
out = "<" + tag
if attributes:
for attr, value in attributes.items():
out += " " + attr.rstrip('_') + "=\"" + value + "\""
out += ">"
return out
以便它自动从任何和所有属性中删除多余的下划线。然后你可以调用:
>>> h2('contents', class_='myh2tag', id_='contenttag')
'<h2 class="myh2tag" id="contenttag">contents</h2>'
并解决两个独立的 Python 命名空间冲突,而不将它们作为特殊情况处理。
关于python - 允许使用 token `class` 作为方法签名中的命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13406107/