在python中使用元类实现工厂设计模式

时间:2010-03-14 20:31:08

标签: python factory metaclass

我在元类上发现了很多链接,其中大多数都提到它们对实现工厂方法很有用。你能告诉我一个使用元类来实现设计模式的例子吗?

3 个答案:

答案 0 :(得分:3)

我很想听到人们对此的评论,但我认为这是你想要做的一个例子

class FactoryMetaclassObject(type):
    def __init__(cls, name, bases, attrs):
        """__init__ will happen when the metaclass is constructed: 
        the class object itself (not the instance of the class)"""
        pass

    def __call__(*args, **kw):
        """
        __call__ will happen when an instance of the class (NOT metaclass)
        is instantiated. For example, We can add instance methods here and they will
        be added to the instance of our class and NOT as a class method
        (aka: a method applied to our instance of object).

        Or, if this metaclass is used as a factory, we can return a whole different
        classes' instance

        """
        return "hello world!"

class FactorWorker(object):
  __metaclass__ = FactoryMetaclassObject

f = FactorWorker()
print f.__class__

您将看到的结果是:输入'str'

答案 1 :(得分:2)

您可以在wikibooks/pythonherehere找到一些有用的示例

答案 2 :(得分:0)

没有必要。您可以override a class's __new__() method以返回完全不同的对象类型。