【发布时间】:2020-11-03 17:35:55
【问题描述】:
我在名为 kwargs.py 的文件中定义了以下函数。 (将模块更改为 unpacking.py 使该功能按预期工作)。请参阅问题底部的图片。
def tag(name, *content, cls=None, **attrs):
if cls is not None:
attrs['class'] = cls
if attrs:
attr_str = ''.join(' %s="%s"' % (key,val)
for key, val
in sorted(attrs.items()))
else:
attr_str = ''
if content:
return '\n'.join('<%s%s>%s</%s>' % (name,attr_str,c,name) for c in content)
else:
return '<%s%s />' % (name,attr_str)
执行时
tag('div', 'testing', cls='test', **dict(id=33,alt='this is a test'))
我得到的结果是
'<div alt="this is a test" class="test" id="33">testing</div>'
但是当我执行这个时
tag(**dict(name='div', content=('testing','and testing'), cls='test', id=33, alt='this is a test'))
我只得到
'<div alt="this is a test" class="test" id="33" />'
为什么会分配参数name 而不是content。 (即使元组没有解包,我也希望至少元组本身被分配给 content[0])。
我在这里错过了什么?
【问题讨论】:
标签: python python-3.x