ajknzhol
ajknzhol

Reputation: 6450

Decorator Design Pattern in Python

I am creating a Flask Website and i want to display different logout links based your current page i.e

So far i have tried upto here.

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()

I am getting Attribute error

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

What wrong i am doing and how to rectify it. Please Help.

Upvotes: 1

Views: 101

Answers (2)

Bill Lynch
Bill Lynch

Reputation: 81936

So you have a few lines that looks like this:

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

You probably want them to look like:

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

Upvotes: 2

Elisha
Elisha

Reputation: 4951

set_html returns nothing, but you try to call for format method on its returned value.

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

Upvotes: 0

Related Questions