class PagemodeDict(dict):
    def __init__(self, *args, **kw):
        super(PagemodeDict, self).__init__(*args, **kw)
        self._constraint()

    def __setitem__(self, key, value):
        super(PagemodeDict, self).__setitem__(key, value)
        self._constraint()

    def setdefault(self, key, value):
        value = super(PagemodeDict, self).setdefault(key, value)
        self._constraint()
        return value

    def _constraint(self):
        sset = super(PagemodeDict, self).__setitem__
        ssetdef = super(PagemodeDict, self).setdefault
        if ssetdef('manage', False) == True:
            sset('custom_html_header', False)

本來我要把它叫作 ConstraintDict,不過因為要用在 Django template 裡,所以就改個名字。這又是一篇筆記文,提醒自己在 subclass container 的時候,不要忘記在被 override 的方法裡用 super() 去叫爸爸 container 的方法。

如果在 __setitem__() 裡用到了 self[key] = blah,會遞迴到爆炸。

感覺應該會是蠻好用的 snippet。

ref:

Posted by yungyuc at 12:22, 0 comment, 0 trackback.
Navigate
Add a trackback
Add a comment

Your name. (required)

Your personal website. (optional)

Your email address. Will not show in page. (suggested, but optional)

Text format is "Plain Text".

Enter "VzSWl"
© hover year to navigate month: powered by django