10

メタクラスに関する多くのリンクを見つけましたが、それらのほとんどは、ファクトリ メソッドの実装に役立つと述べています。メタクラスを使用して設計パターンを実装する例を示してもらえますか?

4

3 に答える 3

3

これについて人々のコメントを聞きたいのですが、これはあなたがやりたいことの例だと思います

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'

于 2010-03-14T21:00:51.783 に答える
2

wikibooks/pythonhereおよびhereでいくつかの役立つ例を見つけることができます

于 2010-03-14T20:39:17.847 に答える
1

必要がない。クラスの__new__()メソッドをオーバーライドして、まったく異なるオブジェクト タイプを返すことができます。

于 2010-03-14T20:35:51.687 に答える