Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing the factory design pattern using metaclasses

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?

like image 305
olamundo Avatar asked Mar 14 '10 20:03

olamundo


2 Answers

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'

like image 96
RyanWilcox Avatar answered Nov 15 '22 18:11

RyanWilcox


You can find some helpful examples at wikibooks/python, here and here

like image 32
Joschua Avatar answered Nov 15 '22 19:11

Joschua