我发现了很多关于元类的链接,其中大多数都提到它们对于实现工厂方法很有用。您能给我展示一个使用元类来实现设计模式的示例吗?

有帮助吗?

解决方案

我喜欢听到人们对这个意见,但我认为这是你想要做什么的例子

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'

其他提示

您可以在以下位置找到一些有用的示例 维基教科书/Python, 这里这里

有没有必要。您可以覆盖类的__new__()方法为了回报一个完全不同的对象类型。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top