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

在python中使用元类实现工厂设计模式,python,factory,metaclass,Python,Factory,Metaclass,我在元类上找到了很多链接,大多数都提到它们对实现工厂方法很有用。你能给我举一个使用元类实现设计模式的例子吗?没有必要。您可以选择返回一个完全不同的对象类型。您可以在上找到一些有用的示例,我很想听听人们对这方面的评论,但我认为这是您想要做的一个示例 class FactoryMetaclassObject(type): def __init__(cls, name, bases, attrs): """__init__ will happen when the metacl

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

没有必要。您可以选择返回一个完全不同的对象类型。

您可以在上找到一些有用的示例,

我很想听听人们对这方面的评论,但我认为这是您想要做的一个示例

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'

我认为您无法使用元类。。。(也许你可以——如果是这样,让我知道,我会学到一些东西:))这些正是我偶然发现的链接。我找不到任何一个工厂的具体例子(尽管他们都提到过),你的O'Reilly和IBM的链接都过时了。(十年后不奇怪!)请考虑刷新它们并张贴一些内容。你能在这个例子中添加一点“因子”吗?我在找更详细的东西。