brysj22952 avatar

PyH源码解析(3)

brysj22952

Published: 10 Aug 2018 › Updated: 10 Aug 2018

PyH源码解析(3)

添加Tag对象内容

通过构造函数传递Tag内容

用户使用场景如下:

>>> a=div('test')
>>> print(a)
<div>
test
</div>

实现原理

Tag对象继承自list对象,list对象中存放的是Tag对象的内容或者子Tag对象,所以,新增这些内容或者子Tag对象,只是简单的调用addObj函数,而这个函数也只是简单的调用list的append函数,增加到列表中。如下:

def addObj(self, obj):#{{{
| 44 id = self.setID(obj)
| 45 setattr(self, id, obj)
| 46 self.append(obj)
| 47 #}}}

至于setID()和setattr()的作用,我们后续再讲。

打印Tag对象的子Tag和内容

知道了Tag对象和子Tag和内容存放在list中,就知道如何打印他们了,核心代码如下所示:

for c in self: 
88 if isinstance(c, Tag): 
89 result += c.render() 
90 else: 
91 result += c 

Leave PyH源码解析(3) to:

Written by

Read more #cn posts


Best Posts From brysj22952

We have not curated any of brysj22952's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From brysj22952