Python中的装饰设计模式

时间:2014-01-09 17:43:03

标签: python

我正在创建一个Flask网站,我希望根据您当前的页面显示不同的注销链接,即

  • 如果我们在主页上登录,请将此链接包含在h2标记
  • 如果我们在不同的页面上并登录,请将此链接包含在下划线标记中
  • 如果我们已登录,请将此链接包含在强标记中

到目前为止,我已经尝试过了。

class HtmlLinks():
    html =""
    def set_html(self, html):
        self.html = html

    def get_html(self):
        return self.html

    def render(self):
        print(self.html)


class LogoutLink(HtmlLinks):
    def __init__(self):
        self.html = "Logout"

class LogoutLinkH2Decorator(HtmlLinks):
    def __init__(self, logout_link):
        self.logout_link = logout_link
        self.set_html("<h2> {0} </h2>").format(self.logout_link.get_html())

    def call(self, name, args):
        self.logout_link.name(args[0])

class LogoutLinkUnderlineDecorator(HtmlLinks):
    def __init__(self, logout_link):
        self.logout_link = logout_link
        self.set_html("<u> {0} </u>").format(self.logout_link.get_html())

    def call(self, name, args):
        self.logout_link.name(args[0])

class LogoutLinkStrongDecorator(HtmlLinks):
    def __init__(self, logout_link):
        self.logout_link = logout_link
        self.set_html("<strong> {0} </strong>").format(self.logout_link.get_html())

    def call(self, name, args):
        self.logout_link.name(args[0])

logout_link = LogoutLink()
is_logged_in = 0
in_home_page = 0

if is_logged_in:
    logout_link = LogoutLinkStrongDecorator(logout_link)
if in_home_page:
    logout_link = LogoutLinkH2Decorator(logout_link)
else:
    logout_link = LogoutLinkUnderlineDecorator(logout_link)

logout_link.render()

我收到属性错误

AttributeError: 'NoneType' object has no attribute 'format'

我在做什么,以及如何纠正它。请帮助。

2 个答案:

答案 0 :(得分:3)

所以你有几行看起来像这样:

    self.set_html("<h2> {0} </h2>").format(self.logout_link.get_html())

您可能希望它们看起来像:

    self.set_html("<h2> {0} </h2>".format(self.logout_link.get_html()))

答案 1 :(得分:1)

set_html不返回任何内容,但您尝试在其返回值上调用format方法。

self.set_html("<strong> {0} </strong>").format(self.logout_link.get_html())