【发布时间】:2014-01-09 16:35:19
【问题描述】:
我正在尝试实现工厂设计模式,并且到目前为止一直在这样做。
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()
输出应该是所有按钮类型的 HTML。
我收到这样的错误
AttributeError: 'str' object has no attribute 'baseclass'
我正在尝试实现一个具有不同变体的类,例如 ImageButton、InputButton 和 FlashButton。根据不同的地方,可能需要为按钮创建不同的html
【问题讨论】:
-
好吧,你将一个字符串(例如
'image')作为参数传递给create_button()。也许您打算传递image(对具有baseclass属性的实际类的引用)。 -
您也可以使用不带参数的
get_html,而它需要 1(self除外)。目前尚不清楚您要从代码中做什么。 -
@Elisha 我正在尝试实现一个具有不同变体的类,例如 ImageButton、InputButton 和 FlashButton。根据位置的不同,可能需要为按钮创建不同的 html。
-
您的问题已经得到解答,但我仍然想说,在普通函数可以使用的情况下使用类是非常不符合 Python 的。