简体   繁体   English

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

[英]Implementing the factory design pattern using metaclasses in python

I found a lot of links on metaclasses, and most of them mention that they are useful for implementing factory methods. 我在元类上发现了很多链接,并且大多数都提到它们对于实现工厂方法很有用。 Can you show me an example of using metaclasses to implement the design pattern? 你能告诉我一个使用元类来实现设计模式的例子吗?

I'd love to hear people's comments on this, but I think this is an example of what you want to do 我很想听到人们对此的评论,但我认为这是你想要做的一个例子

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__

The result you will see is: type 'str' 您将看到的结果是:输入'str'

你可以在wikibooks / python 这里这里找到一些有用的例子

There's no need. 没有必要。 You can override a class's __new__() method in order to return a completely different object type. 您可以覆盖类的__new__()方法 ,以便返回完全不同的对象类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM