Factory Design Pattern

design-patterns, python

Solution

You are trying to call `baseclass` attribute of `str`, which does not exist, because `b` gets string values (one of `['image', 'input', 'flash']`). If you want to create an object according to a string representing its name, you can use the `globals()` dictionary, which holds a mapping between variable names and their values.

class Button(object):
    html = ""
    def get_html(self):
        return self.html

class Image(Button):
    html = "<img></img>"

class Input(Button):
    html = "<input></input>"

class Flash(Button):
    html = "<obj></obj>"

class ButtonFactory():
    def create_button(self, typ):
        targetclass = typ.capitalize()
        return globals()[targetclass]()

button_obj = ButtonFactory()
button = ['image', 'input', 'flash']
for b in button:
    print button_obj.create_button(b).get_html()

EDIT: Using `globals()` or `locals()` is also not a good practice so, if you can, it is better to create a mapping between the relevant objects and their names, like this:

button_objects = {'image':Image,'flash':Flash,'input':Input}

and replace `create_button` with:

def create_button(self, typ):        
    return button_objects[typ]()

Problem

I am trying to implement Factory Design Pattern and have done this far till now. ``` import abc class Button(object): __metaclass__ = abc.ABCMeta html = "" def get_html(self, html): return self.html class ButtonFactory(): def create_button(self, type): baseclass = Button() targetclass = type.baseclass.capitalize() return targetclass button_obj = ButtonFactory() button = ['image', 'input', 'flash'] for b in button: print button_obj.create_button(b).get_html() ``` The output should be the HTML of all your button types. I get the error like this ``` AttributeError: 'str' object has no attribute 'baseclass' ``` I am trying to implement a class which has different variations, such as ImageButton, InputButton and FlashButton. Depending on the place, it may need to create different html for the buttons

Original source