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?
Asked
Active
Viewed 7,239 times
3 Answers
3
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'

RyanWilcox
- 13,890
- 1
- 36
- 60
-
2can you add a little "factoriness" to the example, i.e some customization applied to the created objects? – olamundo Mar 14 '10 at 21:03
2
You can find some helpful examples at wikibooks/python, here and here

Joschua
- 5,816
- 5
- 33
- 44
-
3those are exactly the links I stumbled on. I couldn't find a concrete example of a factory (though all of them mention it) in any of them... – olamundo Mar 14 '10 at 21:01
-
Your O'Reilly and IBM links are stale. (Not surprising after a decade!) Please consider refreshing them and posting some of the contents. – rajah9 Jun 10 '21 at 11:24
1
There's no need. You can override a class's __new__()
method in order to return a completely different object type.

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
-
I don't think you can with metaclasses... (maybe you can - if so let me know and I will have learned something :) ) – RyanWilcox Mar 14 '10 at 20:52
-