setattr question

Gerard Flanagan grflanagan at yahoo.co.uk
Thu Mar 2 11:48:10 EST 2006


Hello

I have the following code:

#### builder.py #########
class HtmlBuilder(object):

    @staticmethod
    def page(title=''):
        return HtmlPage(title)

    @staticmethod
    def element(tag, text=None, **attribs):
        return HtmlElement(tag, text, **attribs)

    @staticmethod
    def literal(text):
        return HtmlLiteral(text)

class HtmlElementFactory(object):

    def __init__(self):
        for tag in ['li', 'ul']:
            setattr( self, tag, HtmlBuilder.element(tag) )

#########################

and so I can do the following:

    html = HtmlElementFactory()
    ul = html.ul
    ul.attrib['class'] = 'default'
    for i in range(3):
        li = html.li
        li.text = 'ghfhj'
        ul.append(li)
    print ul.to_string()

but what I'd like to do is:

    html = HtmlElementFactory()
    ul = html.ul( class='default' )
    for i in range(3):
        ul.append( html.li( 'ghfhj' )
    print ul.to_string()

ie. to pass along *args and **kwargs to the HtmlElement constructor.
Any suggestions?  Or is there a better way to this kind of thing?

thanks

Gerard




More information about the Python-list mailing list