Я нашел много ссылок на метаклассы, и большинство из них упоминает, что они полезны для реализации методов фабрики. Можно ли показать мне пример использования метаклассов для реализации шаблона разработки?
Я бы хотел услышать комментарии людей по этому поводу, но я думаю, что это пример того, что вы хотите сделать
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 , здесь и здесь
В этом нет необходимости. Вы можете переопределить метод класса __ new __ ()
, чтобы вернуть объект совершенно другого типа.