【发布时间】:2011-01-27 11:16:53
【问题描述】:
我发现了很多关于元类的链接,其中大多数都提到它们对于实现工厂方法很有用。你能告诉我一个使用元类来实现设计模式的例子吗?
【问题讨论】:
-
接受的答案是否令人满意?我有点想找一些更详细的东西。
我发现了很多关于元类的链接,其中大多数都提到它们对于实现工厂方法很有用。你能告诉我一个使用元类来实现设计模式的例子吗?
【问题讨论】:
我很想听听人们对此的看法,但我认为这是你想做的一个例子
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__
你会看到的结果是:type 'str'
【讨论】:
您可以在wikibooks/python、here 和here 找到一些有用的示例
【讨论】:
没必要。您可以override a class's __new__() method 以返回完全不同的对象类型。
【讨论】:
__new__() 可以返回任何东西。