質問

メタクラスとは何ですか?何に使用するのですか?

役に立ちましたか?

解決

メタクラスはクラスのクラスです。クラスは、クラスのインスタンスがどのように動作するかを定義します(つまり、オブジェクト)は動作しますが、メタクラスはクラスの動作方法を定義します。クラスはメタクラスのインスタンスです。

Python では、メタクラスに任意の呼び出し可能オブジェクトを使用できます (例: ジェルブ を示しています)、より良いアプローチは、それを実際のクラス自体にすることです。 type Python の通常のメタクラスです。 type それ自体がクラスであり、それ自体の型です。次のようなものを再作成することはできません type 純粋に Python ですが、Python には少しチートが含まれています。Python で独自のメタクラスを作成するには、実際にはサブクラス化するだけです。 type.

メタクラスは、クラス ファクトリとして最も一般的に使用されます。クラスを呼び出してオブジェクトを作成すると、Python はメタクラスを呼び出して (「class」 ステートメントを実行するときに) 新しいクラスを作成します。ノーマルと組み合わせると __init__ そして __new__ したがって、メソッド、メタクラスを使用すると、クラスの作成時に、新しいクラスをレジストリに登録したり、クラスを完全に別のものに置き換えたりするなど、「追加のこと」を行うことができます。

とき class ステートメントが実行されると、Python は最初にステートメントの本文を実行します。 class ステートメントを通常のコード ブロックとして扱います。結果として得られる名前空間 (辞書) には、将来のクラスの属性が保持されます。メタクラスは、クラスの基本クラス (メタクラスは継承されます) を参照して決定されます。 __metaclass__ 将来のクラスの属性 (存在する場合)、または __metaclass__ グローバル変数。次に、クラスの名前、ベース、および属性を使用してメタクラスが呼び出され、インスタンスが作成されます。

ただし、メタクラスは実際に タイプ 単なるファクトリーではなく、クラスの一部であるため、それらを使用してさらに多くのことができます。たとえば、メタクラスで通常のメソッドを定義できます。これらのメタクラス メソッドは、インスタンスなしでクラスに対して呼び出すことができるという点でクラス メソッドに似ていますが、クラスのインスタンスに対して呼び出すことができないという点ではクラス メソッドにも似ていません。 type.__subclasses__() のメソッドの例です。 type メタクラス。次のような通常の「マジック」メソッドを定義することもできます。 __add__, __iter__ そして __getattr__, 、クラスの動作を実装または変更します。

以下に断片を集約した例を示します。

def make_hook(f):
    """Decorator to turn 'foo' method into '__foo__'"""
    f.is_hook = 1
    return f

class MyType(type):
    def __new__(mcls, name, bases, attrs):

        if name.startswith('None'):
            return None

        # Go over attributes and see if they should be renamed.
        newattrs = {}
        for attrname, attrvalue in attrs.iteritems():
            if getattr(attrvalue, 'is_hook', 0):
                newattrs['__%s__' % attrname] = attrvalue
            else:
                newattrs[attrname] = attrvalue

        return super(MyType, mcls).__new__(mcls, name, bases, newattrs)

    def __init__(self, name, bases, attrs):
        super(MyType, self).__init__(name, bases, attrs)

        # classregistry.register(self, self.interfaces)
        print "Would register class %s now." % self

    def __add__(self, other):
        class AutoClass(self, other):
            pass
        return AutoClass
        # Alternatively, to autogenerate the classname as well as the class:
        # return type(self.__name__ + other.__name__, (self, other), {})

    def unregister(self):
        # classregistry.unregister(self)
        print "Would unregister class %s now." % self

class MyObject:
    __metaclass__ = MyType


class NoneSample(MyObject):
    pass

# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)

class Example(MyObject):
    def __init__(self, value):
        self.value = value
    @make_hook
    def add(self, other):
        return self.__class__(self.value + other.value)

# Will unregister the class
Example.unregister()

inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()

print inst + inst
class Sibling(MyObject):
    pass

ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__

他のヒント

オブジェクトとしてのクラス

メタクラスを理解する前に、Python のクラスをマスターする必要があります。そして Python は、Smalltalk 言語から借用した、クラスとは何かという非常に独特な考え方を持っています。

ほとんどの言語では、クラスはオブジェクトの生成方法を記述する単なるコードの一部です。それは Python にも当てはまります。

>>> class ObjectCreator(object):
...       pass
...

>>> my_object = ObjectCreator()
>>> print(my_object)
<__main__.ObjectCreator object at 0x8974f2c>

しかし、Python ではクラスはそれ以上のものです。クラスもオブジェクトです。

はい、オブジェクトです。

キーワードを使用するとすぐに class, 、Pythonはそれを実行し、オブジェクトを作成します。指示

>>> class ObjectCreator(object):
...       pass
...

「ObjectCreator」という名前のオブジェクトをメモリ内に作成します。

このオブジェクト(クラス)はそれ自体がオブジェクト(インスタンス)を作成することができます、そして、これがそれがクラスである理由です.

しかし、それでも、それはオブジェクトであるため、次のようになります。

  • それを変数に割り当てることができます
  • それをコピーできます
  • 属性を追加できます
  • 関数パラメータとして渡すことができます

例えば。:

>>> print(ObjectCreator) # you can print a class because it's an object
<class '__main__.ObjectCreator'>
>>> def echo(o):
...       print(o)
...
>>> echo(ObjectCreator) # you can pass a class as a parameter
<class '__main__.ObjectCreator'>
>>> print(hasattr(ObjectCreator, 'new_attribute'))
False
>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class
>>> print(hasattr(ObjectCreator, 'new_attribute'))
True
>>> print(ObjectCreator.new_attribute)
foo
>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable
>>> print(ObjectCreatorMirror.new_attribute)
foo
>>> print(ObjectCreatorMirror())
<__main__.ObjectCreator object at 0x8997b4c>

クラスを動的に作成する

クラスはオブジェクトであるため、他のオブジェクトと同様に、その場でクラスを作成できます。

まず、次を使用して関数内にクラスを作成できます。 class:

>>> def choose_class(name):
...     if name == 'foo':
...         class Foo(object):
...             pass
...         return Foo # return the class, not an instance
...     else:
...         class Bar(object):
...             pass
...         return Bar
...
>>> MyClass = choose_class('foo')
>>> print(MyClass) # the function returns a class, not an instance
<class '__main__.Foo'>
>>> print(MyClass()) # you can create an object from this class
<__main__.Foo object at 0x89c6d4c>

ただし、クラス全体を自分で記述する必要があるため、それほど動的ではありません。

クラスはオブジェクトであるため、何かによって生成される必要があります。

を使用するときは、 class キーワードを入力すると、Python はこのオブジェクトを自動的に作成します。しかし、Pythonのほとんどのものと同様に、それはあなたに手動でそれを行う方法を与えます。

関数を覚えておいてください type?オブジェクトがどのようなタイプであるかを知ることができる古き良き機能:

>>> print(type(1))
<type 'int'>
>>> print(type("1"))
<type 'str'>
>>> print(type(ObjectCreator))
<type 'type'>
>>> print(type(ObjectCreator()))
<class '__main__.ObjectCreator'>

良い、 type はまったく異なる能力を持ち、その場でクラスを作成することもできます。 type クラスの説明をパラメーターとして取得し、クラスを返すことができます。

(同じ関数に渡すパラメーターに応じて、まったく異なる 2 つの用途があるというのは愚かなことです。Pythonの後方互換性のために問題です)

type このように動作します:

type(name of the class,
     tuple of the parent class (for inheritance, can be empty),
     dictionary containing attributes names and values)

例えば。:

>>> class MyShinyClass(object):
...       pass

次の方法で手動で作成できます。

>>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object
>>> print(MyShinyClass)
<class '__main__.MyShinyClass'>
>>> print(MyShinyClass()) # create an instance with the class
<__main__.MyShinyClass object at 0x8997cec>

クラスの名前として、またクラスの参照を保持する変数として「myshinyclass」を使用していることに気付くでしょう。それらは異なる場合がありますが、物事を複雑にする理由はありません。

type クラスの属性を定義するための辞書を受け入れます。それで:

>>> class Foo(object):
...       bar = True

次のように翻訳できます。

>>> Foo = type('Foo', (), {'bar':True})

そして通常のクラスとして使用されます:

>>> print(Foo)
<class '__main__.Foo'>
>>> print(Foo.bar)
True
>>> f = Foo()
>>> print(f)
<__main__.Foo object at 0x8a9b84c>
>>> print(f.bar)
True

そしてもちろん、それを継承することもできます。

>>>   class FooChild(Foo):
...         pass

だろう:

>>> FooChild = type('FooChild', (Foo,), {})
>>> print(FooChild)
<class '__main__.FooChild'>
>>> print(FooChild.bar) # bar is inherited from Foo
True

最終的には、クラスにメソッドを追加することになります。適切な署名を使用して関数を定義し、属性として割り当てるだけです。

>>> def echo_bar(self):
...       print(self.bar)
...
>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})
>>> hasattr(Foo, 'echo_bar')
False
>>> hasattr(FooChild, 'echo_bar')
True
>>> my_foo = FooChild()
>>> my_foo.echo_bar()
True

また、通常に作成されたクラス オブジェクトにメソッドを追加するのと同じように、クラスを動的に作成した後、さらにメソッドを追加できます。

>>> def echo_bar_more(self):
...       print('yet another method')
...
>>> FooChild.echo_bar_more = echo_bar_more
>>> hasattr(FooChild, 'echo_bar_more')
True

私たちがどこに向かっているのかがわかります:Python ではクラスはオブジェクトであり、その場で動的にクラスを作成できます。

これは、キーワードを使用した場合の Python の動作です。 class, 、これはメタクラスを使用して行われます。

メタクラスとは (最後に)

メタクラスはクラスを作成する「もの」です。

オブジェクトを作成するにはクラスを定義しますよね?

しかし、Python クラスはオブジェクトであることがわかりました。

メタクラスはこれらのオブジェクトを作成するものです。彼らはクラスのクラスです、あなたはそれらをこのように描くことができます:

MyClass = MetaClass()
my_object = MyClass()

あなたはそれを見たことがあります type 次のようなことができます:

MyClass = type('MyClass', (), {})

機能だからね type 実際にはメタクラスです。 type Pythonが使用するMetaclassは、舞台裏のすべてのクラスを作成することです。

さて、一体なぜ小文字で書かれていないのか疑問に思うでしょう。 Type?

まあ、それは一貫性の問題だと思います str, 、文字列オブジェクトを作成するクラスと int 整数オブジェクトを作成するクラス。 type クラスオブジェクトを作成するクラスです。

をチェックするとわかります __class__ 属性。

すべて、つまりすべてが Python のオブジェクトです。これには、INT、文字列、関数、クラスが含まれます。それらはすべてオブジェクトです。そして、それらはすべてクラスから作成されました:

>>> age = 35
>>> age.__class__
<type 'int'>
>>> name = 'bob'
>>> name.__class__
<type 'str'>
>>> def foo(): pass
>>> foo.__class__
<type 'function'>
>>> class Bar(object): pass
>>> b = Bar()
>>> b.__class__
<class '__main__.Bar'>

さて、何ですか? __class__ どれかの __class__ ?

>>> age.__class__.__class__
<type 'type'>
>>> name.__class__.__class__
<type 'type'>
>>> foo.__class__.__class__
<type 'type'>
>>> b.__class__.__class__
<type 'type'>

したがって、メタクラスはクラス オブジェクトを作成するものにすぎません。

必要に応じて、これを「クラスファクトリー」と呼ぶこともできます。

type Pythonが使用する組み込みのMetaclassですが、もちろん、独自のMetaclassを作成できます。

__metaclass__ 属性

Python 2 では、 __metaclass__ クラスを作成するときに属性を使用します (Python 3 構文については次のセクションを参照)。

class Foo(object):
    __metaclass__ = something...
    [...]

これを行うと、Python はメタクラスを使用してクラスを作成します。 Foo.

注意してください、それは難しいです。

あなたが書く class Foo(object) まず、クラスオブジェクト Foo まだメモリに作成されていません。

Python が探します __metaclass__ クラス定義で。見つけた場合、それはそれを使用してオブジェクトクラスを作成します Foo. 。そうでない場合は、使用されますtype クラスを作成します。

それを何度か読んでください。

実行する場合:

class Foo(Bar):
    pass

Python は次のことを行います。

ありますか __metaclass__ の属性 Foo?

「はい」の場合は、次の名前のクラス オブジェクト (クラス オブジェクトと言いましたが、ここではそのままにしておきます) をメモリ内に作成します。 Foo 入っているものを使って __metaclass__.

Python が見つからない場合 __metaclass__, を探します。 __metaclass__ MODULE レベルで同じことを試してみます (ただし、何も継承しないクラス、基本的には古いスタイルのクラスに限ります)。

それで何も見つからなかったら __metaclass__ まったく、それは Barの(最初の親)独自のメタクラス(デフォルトである可能性があります) type) クラスオブジェクトを作成します。

ここで注意してください。 __metaclass__ 属性は継承されず、親のメタクラス(Bar.__class__)となります。もし Bar を使用しました __metaclass__ 作成した属性 Bartype() (そうではない type.__new__())、サブクラスはその動作を継承しません。

ここで大きな問題は、何を入れることができるかということです __metaclass__ ?

答えは次のとおりです。クラスを作成できるもの。

そして、クラスを作成できるものは何でしょうか? type, 、またはそれをサブクラス化または使用するもの。

Python 3 のメタクラス

メタクラスを設定する構文は Python 3 で変更されました。

class Foo(object, metaclass=something):
    ...

つまりの __metaclass__ 属性は使用されなくなり、基本クラスのリスト内のキーワード引数が使用されます。

ただし、メタクラスの動作はそのままです ほぼ同じ.

Python 3 のメタクラスに追加された点の 1 つは、次のように属性をキーワード引数としてメタクラスに渡すこともできることです。

class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):
    ...

Python がこれをどのように処理するかについては、以下のセクションをお読みください。

カスタムメタクラス

メタクラスの主な目的は、クラスが作成されたときに自動的に変更することです。

通常、APIでこれを行います。APIでは、現在のコンテキストに一致するクラスを作成したい場合があります。

愚かな例を想像してください。モジュール内のすべてのクラスが大文字で属性を記述する必要があると判断します。これを行うにはいくつかの方法がありますが、1つの方法は設定することです __metaclass__ モジュールレベルで。

このようにして、このモジュールのすべてのクラスがこのメタラスを使用して作成され、すべての属性を大文字に変えるようにメタラスに指示する必要があります。

幸いなことに、 __metaclass__ 実際にはあらゆる呼び出すことができます。正式なクラスである必要はありません(名前に「クラス」があるものは、クラスである必要はありません。でも役に立ちます)。

そこで、関数を使用した簡単な例から始めます。

# the metaclass will automatically get passed the same argument
# that you usually pass to `type`
def upper_attr(future_class_name, future_class_parents, future_class_attr):
    """
      Return a class object, with the list of its attribute turned
      into uppercase.
    """

    # pick up any attribute that doesn't start with '__' and uppercase it
    uppercase_attr = {}
    for name, val in future_class_attr.items():
        if not name.startswith('__'):
            uppercase_attr[name.upper()] = val
        else:
            uppercase_attr[name] = val

    # let `type` do the class creation
    return type(future_class_name, future_class_parents, uppercase_attr)

__metaclass__ = upper_attr # this will affect all classes in the module

class Foo(): # global __metaclass__ won't work with "object" though
    # but we can define __metaclass__ here instead to affect only this class
    # and this will work with "object" children
    bar = 'bip'

print(hasattr(Foo, 'bar'))
# Out: False
print(hasattr(Foo, 'BAR'))
# Out: True

f = Foo()
print(f.BAR)
# Out: 'bip'

ここで、まったく同じことを行いますが、メタクラスに実際のクラスを使用します。

# remember that `type` is actually a class like `str` and `int`
# so you can inherit from it
class UpperAttrMetaclass(type):
    # __new__ is the method called before __init__
    # it's the method that creates the object and returns it
    # while __init__ just initializes the object passed as parameter
    # you rarely use __new__, except when you want to control how the object
    # is created.
    # here the created object is the class, and we want to customize it
    # so we override __new__
    # you can do some stuff in __init__ too if you wish
    # some advanced use involves overriding __call__ as well, but we won't
    # see this
    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attr):

        uppercase_attr = {}
        for name, val in future_class_attr.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return type(future_class_name, future_class_parents, uppercase_attr)

しかし、これは実際には OOP ではありません。私たちは電話します type 直接的かつ私たちは親を無効にしたり、電話したりしません __new__. 。やりましょう:

class UpperAttrMetaclass(type):

    def __new__(upperattr_metaclass, future_class_name,
                future_class_parents, future_class_attr):

        uppercase_attr = {}
        for name, val in future_class_attr.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        # reuse the type.__new__ method
        # this is basic OOP, nothing magic in there
        return type.__new__(upperattr_metaclass, future_class_name,
                            future_class_parents, uppercase_attr)

追加の引数に気づいたかもしれません upperattr_metaclass. 。それについて特別なことは何もありません: __new__ 常に最初のパラメータとして定義されているクラスを受け取ります。あなたと同じように self インスタンスを最初のパラメータとして受け取る通常のメソッドの場合、またはクラス メソッドの定義クラスの場合。

もちろん、私がここで使用した名前は明確にするために長いですが、 self, 、すべての引数には従来の名前が付いています。したがって、実際の生産メタラスは次のようになります:

class UpperAttrMetaclass(type):

    def __new__(cls, clsname, bases, dct):

        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return type.__new__(cls, clsname, bases, uppercase_attr)

を使用すると、さらにきれいにすることができます super, これにより、継承が容易になります (はい、メタクラスから継承したり、型から継承したりするメタクラスを持つことができるため)。

class UpperAttrMetaclass(type):

    def __new__(cls, clsname, bases, dct):

        uppercase_attr = {}
        for name, val in dct.items():
            if not name.startswith('__'):
                uppercase_attr[name.upper()] = val
            else:
                uppercase_attr[name] = val

        return super(UpperAttrMetaclass, cls).__new__(cls, clsname, bases, uppercase_attr)

ああ、Python 3 では、次のようにキーワード引数を使用してこの呼び出しを実行すると、次のようになります。

class Foo(object, metaclass=Thing, kwarg1=value1):
    ...

これを使用するには、メタクラスでこれを次のように変換します。

class Thing(type):
    def __new__(cls, clsname, bases, dct, kwargs1=default):
        ...

それでおしまい。メタクラスについては、実際にはこれ以上何もありません。

メタクラスを使用してコードの複雑さの背後にある理由はメタクラスのためではありません。それは通常、メタクラスを使用して内省、継続の操作、varsに依存してねじれたものを行うためです。 __dict__, 、など。

実際、メタクラスは黒魔術を行うのに特に便利であり、したがって複雑なものです。しかし、それ自体は単純です。

  • クラスの作成をインターセプトする
  • クラスを変更する
  • 変更されたクラスを返す

なぜ関数ではなくメタクラスクラスを使用するのでしょうか?

以来 __metaclass__ 呼び出し可能なものを受け入れることができますが、なぜクラスは明らかに複雑であるため、クラスを使用するのですか?

そうする理由はいくつかあります。

  • 意図は明らかだ。読むとき UpperAttrMetaclass(type), 、あなたは何が続くか知っています
  • OOPを使用できます。メタクラスはメタクラスから継承し、親メソッドをオーバーライドできます。メタクラスはメタクラスを使用することもできます。
  • メタクラス関数を使用せずにメタクラスクラスを指定した場合、クラスのサブクラスはそのメタクラスのインスタンスになります。
  • コードをより適切に構造化できます。上記の例ほど些細なものにメタラスを使用することはありません。通常、それは何か複雑なもののためです。いくつかの方法を作成して1つのクラスにグループ化する機能を持つことは、コードを読みやすくするのに非常に役立ちます。
  • 引っ掛けることができます __new__, __init__ そして __call__. 。これにより、さまざまなことをすることができます。普段は全部できても __new__、一部の人々はより快適です __init__.
  • これらはメタクラスと呼ばれます。それは何か意味があるはずです!

なぜメタクラスを使用するのでしょうか?

さて、大きな質問です。なぜ、エラーが発生しやすい不明瞭な機能を使用するのでしょうか?

まあ、通常はそうではありません:

メタクラスは、ユーザーの99%が心配すべきではない、より深い魔法です。あなたがそれらを必要としているかどうか疑問に思うなら、あなたはそうしません(実際に彼らを必要とする人々は、彼らが彼らを必要としていることを確実に知っていて、理由について説明する必要はありません)。

Python の第一人者ティム・ピーターズ

メタクラスの主な使用例は、API の作成です。この典型的な例は Django ORM です。

次のようなものを定義できます。

class Person(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()

しかし、これを行うと:

guy = Person(name='bob', age='35')
print(guy.age)

返されません IntegerField 物体。返されます int, 、データベースから直接取得することもできます。

これが可能なのは、 models.Model 定義する __metaclass__ そして、それを変える魔法を使用します Person データベースフィールドへの複雑なフックに簡単なステートメントで定義しました。

Djangoは、シンプルなAPIを公開してメタクラスを使用して、このAPIからコードを再現して舞台裏で実際の仕事をすることで、複雑なものをシンプルに見せます。

最後の言葉

まず、クラスはインスタンスを作成できるオブジェクトであることを知っています。

実際、クラス自体がインスタンスです。メタクラスの。

>>> class Foo(object): pass
>>> id(Foo)
142630324

すべてがPythonのオブジェクトであり、それらはすべてクラスのインスタンスまたはメタクラスのインスタンスのいずれかです。

を除いて type.

type 実際には独自のメタクラスです。これは、純粋なPythonで再現できるものではなく、実装レベルで少し不正行為をすることで行われます。

次に、メタクラスは複雑です。非常にシンプルなクラスの変更に使用したくない場合があります。クラスを変更するには、次の 2 つの異なる手法を使用します。

クラス変更が必要な場合は 99% の場合、これらを使用する方が良いでしょう。

ただし、98% の場合、クラスを変更する必要はまったくありません。

この回答は 2008 年に書かれた Python 2.x 用であり、3.x ではメタクラスが若干異なることに注意してください。

メタクラスは、「クラス」を機能させる秘密のソースです。新しいスタイル オブジェクトのデフォルトのメタクラスは「type」と呼ばれます。

class type(object)
  |  type(object) -> the object's type
  |  type(name, bases, dict) -> a new type

メタクラスは 3 つの引数を受け取ります。'名前', '基地' そして '辞書'

ここからが秘密の始まりです。このクラス定義例で、名前、基底、辞書がどこから来たのかを探してください。

class ThisIsTheName(Bases, Are, Here):
    All_the_code_here
    def doesIs(create, a):
        dict

' の方法を示すメタクラスを定義しましょう。クラス:』と呼んでいます。

def test_metaclass(name, bases, dict):
    print 'The Class Name is', name
    print 'The Class Bases are', bases
    print 'The dict has', len(dict), 'elems, the keys are', dict.keys()

    return "yellow"

class TestName(object, None, int, 1):
    __metaclass__ = test_metaclass
    foo = 1
    def baz(self, arr):
        pass

print 'TestName = ', repr(TestName)

# output => 
The Class Name is TestName
The Class Bases are (<type 'object'>, None, <type 'int'>, 1)
The dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']
TestName =  'yellow'

ここで、実際に何かを意味する例を示します。これにより、リスト内の変数が自動的にクラスに設定された「属性」になり、None に設定されます。

def init_attributes(name, bases, dict):
    if 'attributes' in dict:
        for attr in dict['attributes']:
            dict[attr] = None

    return type(name, bases, dict)

class Initialised(object):
    __metaclass__ = init_attributes
    attributes = ['foo', 'bar', 'baz']

print 'foo =>', Initialised.foo
# output=>
foo => None

'Initialized' がメタクラスを持つことによって得られる魔法の動作に注意してください。 init_attributes Initialized のサブクラスには渡されません。

以下はさらに具体的な例で、「type」をサブクラス化して、クラスの作成時にアクションを実行するメタクラスを作成する方法を示しています。これは非常に難しいです:

class MetaSingleton(type):
    instance = None
    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)
        return cls.instance

 class Foo(object):
     __metaclass__ = MetaSingleton

 a = Foo()
 b = Foo()
 assert a is b

メタクラスの用途の 1 つは、新しいプロパティとメソッドをインスタンスに自動的に追加することです。

たとえば、以下を見てみると、 ジャンゴモデル, 、その定義は少し混乱しているように見えます。クラスのプロパティを定義しているだけのように見えます。

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

ただし、実行時には、Person オブジェクトにはあらゆる種類の便利なメソッドが埋め込まれます。を参照してください。 ソース 素晴らしいメタクラスを実現します。

メタクラスがどのように機能し、Python 型システムにどのように適合するかを説明している人もいます。以下にその使用例を示します。私が作成したテスト フレームワークでは、クラスが定義された順序を追跡し、後でこの順序でクラスをインスタンス化できるようにしたいと考えていました。メタクラスを使用してこれを行うのが最も簡単であることがわかりました。

class MyMeta(type):

    counter = 0

    def __init__(cls, name, bases, dic):
        type.__init__(cls, name, bases, dic)
        cls._order = MyMeta.counter
        MyMeta.counter += 1

class MyType(object):              # Python 2
    __metaclass__ = MyMeta

class MyType(metaclass=MyMeta):    # Python 3
    pass

のサブクラスであるものすべて MyType 次にクラス属性を取得します _order クラスが定義された順序を記録します。

ONLamp のメタクラス プログラミングの入門書はよく書かれており、すでに数年前のものであるにもかかわらず、このトピックへの非常に優れた入門書になっていると思います。

http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html (アーカイブ: https://web.archive.org/web/20080206005253/http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html)

要するに:クラスはインスタンスを作成するための設計図であり、メタクラスはクラスを作成するための設計図です。Python では、この動作を有効にするにはクラスもファーストクラス オブジェクトである必要があることが簡単にわかります。

私は自分でメタクラスを書いたことはありませんが、メタクラスの最も優れた使用法の 1 つは次のようなものに見られると思います。 Django フレームワーク. 。モデル クラスは、メタクラス アプローチを使用して、新しいモデルまたはフォーム クラスを作成する宣言型スタイルを有効にします。メタクラスがクラスを作成している間、すべてのメンバーがクラス自体をカスタマイズできるようになります。

言い残されたことは次のとおりです。メタクラスが何なのかを知らない場合、次のような可能性があります。 それらは必要ないでしょう 99%です。

メタクラスとは何ですか?何に使いますか?

TLDR:クラスがインスタンスを作成してインスタンスの動作を定義するのと同じように、メタクラスはクラスのインスタンスを作成して動作を定義します。

疑似コード:

>>> Class(...)
instance

上記は見覚えがあるはずです。さて、どこにありますか Class から来る?これはメタクラスのインスタンスです (擬似コードでもあります)。

>>> Metaclass(...)
Class

実際のコードでは、デフォルトのメタクラスを渡すことができます。 type, 、クラスをインスタンス化するために必要なものがすべて揃っており、クラスを取得します。

>>> type('Foo', (object,), {}) # requires a name, bases, and a namespace
<class '__main__.Foo'>

別の言い方をすると

  • メタクラスがクラスに対して存在するのと同様に、クラスはインスタンスに対して存在します。

    オブジェクトをインスタンス化すると、インスタンスが取得されます。

    >>> object()                          # instantiation of class
    <object object at 0x7f9069b4e0b0>     # instance
    

    同様に、デフォルトのメタクラスを使用してクラスを明示的に定義すると、 type, 、それをインスタンス化します。

    >>> type('Object', (object,), {})     # instantiation of metaclass
    <class '__main__.Object'>             # instance
    
  • 別の言い方をすると、クラスはメタクラスのインスタンスです。

    >>> isinstance(object, type)
    True
    
  • 3 番目の言い方をすると、メタクラスはクラスのクラスです。

    >>> type(object) == type
    True
    >>> object.__class__
    <class 'type'>
    

クラス定義を作成し、Python がそれを実行すると、メタクラスを使用してクラス オブジェクトがインスタンス化されます (これは、そのクラスのインスタンスをインスタンス化するために使用されます)。

クラス定義を使用してカスタム オブジェクト インスタンスの動作を変更できるのと同じように、メタクラスのクラス定義を使用してクラス オブジェクトの動作を変更できます。

何に使えますか?から ドキュメント:

メタクラスの潜在的な用途は無限です。検討されたアイデアには、ロギング、インターフェイスのチェック、自動委任、自動プロパティ作成、プロキシ、フレームワーク、自動リソース ロック/同期などが含まれます。

それにもかかわらず、どうしても必要な場合を除き、ユーザーはメタクラスの使用を避けることが通常推奨されます。

クラスを作成するたびにメタクラスを使用します。

たとえば次のようにクラス定義を書くと、

class Foo(object): 
    'demo'

クラスオブジェクトをインスタンス化します。

>>> Foo
<class '__main__.Foo'>
>>> isinstance(Foo, type), isinstance(Foo, object)
(True, True)

関数呼び出しと同じです type 適切な引数を指定して、結果をその名前の変数に代入します。

name = 'Foo'
bases = (object,)
namespace = {'__doc__': 'demo'}
Foo = type(name, bases, namespace)

一部の項目は自動的に追加されることに注意してください。 __dict__, 、つまり名前空間:

>>> Foo.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, 
'__module__': '__main__', '__weakref__': <attribute '__weakref__' 
of 'Foo' objects>, '__doc__': 'demo'})

メタクラス どちらの場合も、作成したオブジェクトの内容は次のとおりです。 type.

(授業内容の補足) __dict__: __module__ クラスが定義されている場所を認識する必要があるため、存在します。 __dict__ そして __weakref__ 定義していないから存在するのか __slots__ - もし私達 定義する __slots__ 許可しないので、インスタンス内のスペースを少し節約します。 __dict__ そして __weakref__ それらを除外することによって。例えば:

>>> Baz = type('Bar', (object,), {'__doc__': 'demo', '__slots__': ()})
>>> Baz.__dict__
mappingproxy({'__doc__': 'demo', '__slots__': (), '__module__': '__main__'})

...しかし、私はそれました。)

延長できます type 他のクラス定義と同様に:

ここがデフォルトです __repr__ クラスの数:

>>> Foo
<class '__main__.Foo'>

Python オブジェクトを作成する際にデフォルトでできる最も価値のあることの 1 つは、それに適切な機能を提供することです。 __repr__. 。電話するとき help(repr) 私たちは、人にとって良いテストがあることを知りました。 __repr__ それには同等性のテストも必要です - obj == eval(repr(obj)). 。次の簡単な実装は、 __repr__ そして __eq__ 私たちのタイプのクラスインスタンスの場合、クラスはデフォルトを改善する可能性のあるデモンストレーションを提供します __repr__ クラスの数:

class Type(type):
    def __repr__(cls):
        """
        >>> Baz
        Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
        >>> eval(repr(Baz))
        Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
        """
        metaname = type(cls).__name__
        name = cls.__name__
        parents = ', '.join(b.__name__ for b in cls.__bases__)
        if parents:
            parents += ','
        namespace = ', '.join(': '.join(
          (repr(k), repr(v) if not isinstance(v, type) else v.__name__))
               for k, v in cls.__dict__.items())
        return '{0}(\'{1}\', ({2}), {{{3}}})'.format(metaname, name, parents, namespace)
    def __eq__(cls, other):
        """
        >>> Baz == eval(repr(Baz))
        True            
        """
        return (cls.__name__, cls.__bases__, cls.__dict__) == (
                other.__name__, other.__bases__, other.__dict__)

したがって、このメタクラスを使用してオブジェクトを作成すると、 __repr__ コマンドラインでエコーされると、デフォルトよりもはるかに見苦しくなくなります。

>>> class Bar(object): pass
>>> Baz = Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})
>>> Baz
Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})

素敵な __repr__ クラス インスタンスに対して定義されているため、コードをデバッグする能力が強化されます。ただし、さらに詳しく確認すると、 eval(repr(Class)) 可能性は低いです (関数をデフォルトから評価することはかなり不可能であるため) __repr__さん)。

想定される用途: __prepare__ 名前空間

たとえば、クラスのメソッドがどのような順序で作成されるかを知りたい場合は、クラスの名前空間として順序付き辞書を提供できます。これを行うのは __prepare__ どれの クラスが Python 3 で実装されている場合は、クラスの名前空間辞書を返します。:

from collections import OrderedDict

class OrderedType(Type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwargs):
        return OrderedDict()
    def __new__(cls, name, bases, namespace, **kwargs):
        result = Type.__new__(cls, name, bases, dict(namespace))
        result.members = tuple(namespace)
        return result

そして使用法:

class OrderedMethodsObject(object, metaclass=OrderedType):
    def method1(self): pass
    def method2(self): pass
    def method3(self): pass
    def method4(self): pass

これで、これらのメソッド (および他のクラス属性) が作成された順序の記録が得られました。

>>> OrderedMethodsObject.members
('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4')

この例は、 ドキュメンテーション - 新しい 標準ライブラリの列挙型 これをします。

そこで、クラスを作成してメタクラスをインスタンス化しました。メタクラスを他のクラスと同様に扱うこともできます。メソッド解決順序があります。

>>> inspect.getmro(OrderedType)
(<class '__main__.OrderedType'>, <class '__main__.Type'>, <class 'type'>, <class 'object'>)

そして、それはほぼ正しいです repr (関数を表現する方法が見つからない限り、これを評価することはできません。):

>>> OrderedMethodsObject
OrderedType('OrderedMethodsObject', (object,), {'method1': <function OrderedMethodsObject.method1 at 0x0000000002DB01E0>, 'members': ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4'), 'method3': <function OrderedMet
hodsObject.method3 at 0x0000000002DB02F0>, 'method2': <function OrderedMethodsObject.method2 at 0x0000000002DB0268>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'OrderedMethodsObject' objects>, '__doc__': None, '__d
ict__': <attribute '__dict__' of 'OrderedMethodsObject' objects>, 'method4': <function OrderedMethodsObject.method4 at 0x0000000002DB0378>})

Python3のアップデート

(現時点では) メタクラスには 2 つの主要なメソッドがあります。

  • __prepare__, 、 そして
  • __new__

__prepare__ カスタム マッピング ( OrderedDict) クラスの作成中に名前空間として使用されます。選択した名前空間のインスタンスを返す必要があります。実装しないと __prepare__ 普通の dict 使用されている。

__new__ 最終クラスの実際の作成/変更を担当します。

必要最低限​​の、余分なことは何もしないメタクラスは次のようになります。

class Meta(type):

    def __prepare__(metaclass, cls, bases):
        return dict()

    def __new__(metacls, cls, bases, clsdict):
        return super().__new__(metacls, cls, bases, clsdict)

簡単な例:

属性に対して単純な検証コードを実行したいとします。たとえば、属性は常に int または str. 。メタクラスがない場合、クラスは次のようになります。

class Person:
    weight = ValidateType('weight', int)
    age = ValidateType('age', int)
    name = ValidateType('name', str)

ご覧のとおり、属性の名前を 2 回繰り返す必要があります。これにより、タイプミスが発生しやすくなり、迷惑なバグが発生する可能性があります。

単純なメタクラスでこの問題に対処できます。

class Person(metaclass=Validator):
    weight = ValidateType(int)
    age = ValidateType(int)
    name = ValidateType(str)

これはメタクラスがどのように見えるかです (使用しない場合) __prepare__ 必要ないので):

class Validator(type):
    def __new__(metacls, cls, bases, clsdict):
        # search clsdict looking for ValidateType descriptors
        for name, attr in clsdict.items():
            if isinstance(attr, ValidateType):
                attr.name = name
                attr.attr = '_' + name
        # create final class and return it
        return super().__new__(metacls, cls, bases, clsdict)

以下のサンプル実行:

p = Person()
p.weight = 9
print(p.weight)
p.weight = '9'

生成されるもの:

9
Traceback (most recent call last):
  File "simple_meta.py", line 36, in <module>
    p.weight = '9'
  File "simple_meta.py", line 24, in __set__
    (self.name, self.type, value))
TypeError: weight must be of type(s) <class 'int'> (got '9')

注記:この例は非常に単純なので、クラス デコレーターでも実現できますが、実際のメタクラスではさらに多くの処理が行われると考えられます。

参照用の「ValidateType」クラス:

class ValidateType:
    def __init__(self, type):
        self.name = None  # will be set by metaclass
        self.attr = None  # will be set by metaclass
        self.type = type
    def __get__(self, inst, cls):
        if inst is None:
            return self
        else:
            return inst.__dict__[self.attr]
    def __set__(self, inst, value):
        if not isinstance(value, self.type):
            raise TypeError('%s must be of type(s) %s (got %r)' %
                    (self.name, self.type, value))
        else:
            inst.__dict__[self.attr] = value

メタクラスの役割 __call__() クラスインスタンス作成時のメソッド

数か月以上 Python プログラミングを行っていると、最終的には次のようなコードに遭遇するでしょう。

# define a class
class SomeClass(object):
    # ...
    # some definition here ...
    # ...

# create an instance of it
instance = SomeClass()

# then call the object as if it's a function
result = instance('foo', 'bar')

後者は、を実装すると可能になります。 __call__() クラスのマジックメソッド。

class SomeClass(object):
    # ...
    # some definition here ...
    # ...

    def __call__(self, foo, bar):
        return bar + foo

__call__() メソッドは、クラスのインスタンスが呼び出し可能オブジェクトとして使用されるときに呼び出されます。しかし、前の回答からわかるように、クラス自体はメタクラスのインスタンスであるため、クラスを呼び出し可能として使用するとき(つまり、そのインスタンスを作成するとき)、実際にはそのメタクラスを呼び出しています。 __call__() 方法。この時点で、ほとんどの Python プログラマーは、このようなインスタンスを作成するときに次のように言われたため、少し混乱しています。 instance = SomeClass() あなたはそれを呼んでいます __init__() 方法。もう少し深く調べたことのある人は以前からそれを知っています __init__() あるよ __new__(). 。さて、今日、さらなる真実の層が明らかにされています。 __new__() メタクラスがあります」 __call__().

特にクラスのインスタンスを作成するという観点からメソッド呼び出しチェーンを調べてみましょう。

これは、インスタンスが作成される直前とインスタンスがインスタンスを返そうとしている瞬間を正確に記録するメタクラスです。

class Meta_1(type):
    def __call__(cls):
        print "Meta_1.__call__() before creating an instance of ", cls
        instance = super(Meta_1, cls).__call__()
        print "Meta_1.__call__() about to return instance."
        return instance

これはそのメタクラスを使用するクラスです

class Class_1(object):

    __metaclass__ = Meta_1

    def __new__(cls):
        print "Class_1.__new__() before creating an instance."
        instance = super(Class_1, cls).__new__(cls)
        print "Class_1.__new__() about to return instance."
        return instance

    def __init__(self):
        print "entering Class_1.__init__() for instance initialization."
        super(Class_1,self).__init__()
        print "exiting Class_1.__init__()."

それではインスタンスを作成しましょう Class_1

instance = Class_1()
# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.
# Class_1.__new__() before creating an instance.
# Class_1.__new__() about to return instance.
# entering Class_1.__init__() for instance initialization.
# exiting Class_1.__init__().
# Meta_1.__call__() about to return instance.

上記のコードは実際にはタスクをログに記録する以外のことは何も行っていないことに注目してください。各メソッドは実際の作業をその親の実装に委任するため、デフォルトの動作が維持されます。以来 typeMeta_1の親クラス (type はデフォルトの親メタクラスです)、上記の出力の順序付けシーケンスを考慮すると、次の擬似実装が何になるかについて手がかりが得られます。 type.__call__():

class type:
    def __call__(cls, *args, **kwarg):

        # ... maybe a few things done to cls here

        # then we call __new__() on the class to create an instance
        instance = cls.__new__(cls, *args, **kwargs)

        # ... maybe a few things done to the instance here

        # then we initialize the instance with its __init__() method
        instance.__init__(*args, **kwargs)

        # ... maybe a few more things done to instance here

        # then we return it
        return instance

メタクラスが __call__() メソッドは最初に呼び出されるメソッドです。次に、インスタンスの作成をクラスに委任します。 __new__() メソッドとインスタンスの初期化 __init__(). 。これは、最終的にインスタンスを返すものでもあります。

上記のことから、メタクラスは次のようになります。 __call__() に電話をかけるかどうかを決定する機会も与えられます。 Class_1.__new__() または Class_1.__init__() 最終的には作られます。実行中に、これらのメソッドのいずれにも触れられていないオブジェクトが実際に返される可能性があります。たとえば、シングルトン パターンに対する次のアプローチを考えてみましょう。

class Meta_2(type):
    singletons = {}

    def __call__(cls, *args, **kwargs):
        if cls in Meta_2.singletons:
            # we return the only instance and skip a call to __new__()
            # and __init__()
            print ("{} singleton returning from Meta_2.__call__(), "
                   "skipping creation of new instance.".format(cls))
            return Meta_2.singletons[cls]

        # else if the singleton isn't present we proceed as usual
        print "Meta_2.__call__() before creating an instance."
        instance = super(Meta_2, cls).__call__(*args, **kwargs)
        Meta_2.singletons[cls] = instance
        print "Meta_2.__call__() returning new instance."
        return instance

class Class_2(object):

    __metaclass__ = Meta_2

    def __new__(cls, *args, **kwargs):
        print "Class_2.__new__() before creating instance."
        instance = super(Class_2, cls).__new__(cls)
        print "Class_2.__new__() returning instance."
        return instance

    def __init__(self, *args, **kwargs):
        print "entering Class_2.__init__() for initialization."
        super(Class_2, self).__init__()
        print "exiting Class_2.__init__()."

型のオブジェクトを繰り返し作成しようとすると何が起こるかを観察してみましょう。 Class_2

a = Class_2()
# Meta_2.__call__() before creating an instance.
# Class_2.__new__() before creating instance.
# Class_2.__new__() returning instance.
# entering Class_2.__init__() for initialization.
# exiting Class_2.__init__().
# Meta_2.__call__() returning new instance.

b = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

c = Class_2()
# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.

a is b is c # True

メタクラスは、他の (一部の) クラスを作成する方法を指示するクラスです。

これは、問題の解決策としてメタクラスを見た場合です。私は非常に複雑な問題を抱えており、おそらく別の方法で解決できたはずですが、メタクラスを使用して解決することにしました。複雑なため、これは私がこれまでに書いた数少ないモジュールの 1 つであり、モジュール内のコメントが書かれたコードの量を超えています。ここにあります...

#!/usr/bin/env python

# Copyright (C) 2013-2014 Craig Phillips.  All rights reserved.

# This requires some explaining.  The point of this metaclass excercise is to
# create a static abstract class that is in one way or another, dormant until
# queried.  I experimented with creating a singlton on import, but that did
# not quite behave how I wanted it to.  See now here, we are creating a class
# called GsyncOptions, that on import, will do nothing except state that its
# class creator is GsyncOptionsType.  This means, docopt doesn't parse any
# of the help document, nor does it start processing command line options.
# So importing this module becomes really efficient.  The complicated bit
# comes from requiring the GsyncOptions class to be static.  By that, I mean
# any property on it, may or may not exist, since they are not statically
# defined; so I can't simply just define the class with a whole bunch of
# properties that are @property @staticmethods.
#
# So here's how it works:
#
# Executing 'from libgsync.options import GsyncOptions' does nothing more
# than load up this module, define the Type and the Class and import them
# into the callers namespace.  Simple.
#
# Invoking 'GsyncOptions.debug' for the first time, or any other property
# causes the __metaclass__ __getattr__ method to be called, since the class
# is not instantiated as a class instance yet.  The __getattr__ method on
# the type then initialises the class (GsyncOptions) via the __initialiseClass
# method.  This is the first and only time the class will actually have its
# dictionary statically populated.  The docopt module is invoked to parse the
# usage document and generate command line options from it.  These are then
# paired with their defaults and what's in sys.argv.  After all that, we
# setup some dynamic properties that could not be defined by their name in
# the usage, before everything is then transplanted onto the actual class
# object (or static class GsyncOptions).
#
# Another piece of magic, is to allow command line options to be set in
# in their native form and be translated into argparse style properties.
#
# Finally, the GsyncListOptions class is actually where the options are
# stored.  This only acts as a mechanism for storing options as lists, to
# allow aggregation of duplicate options or options that can be specified
# multiple times.  The __getattr__ call hides this by default, returning the
# last item in a property's list.  However, if the entire list is required,
# calling the 'list()' method on the GsyncOptions class, returns a reference
# to the GsyncListOptions class, which contains all of the same properties
# but as lists and without the duplication of having them as both lists and
# static singlton values.
#
# So this actually means that GsyncOptions is actually a static proxy class...
#
# ...And all this is neatly hidden within a closure for safe keeping.
def GetGsyncOptionsType():
    class GsyncListOptions(object):
        __initialised = False

    class GsyncOptionsType(type):
        def __initialiseClass(cls):
            if GsyncListOptions._GsyncListOptions__initialised: return

            from docopt import docopt
            from libgsync.options import doc
            from libgsync import __version__

            options = docopt(
                doc.__doc__ % __version__,
                version = __version__,
                options_first = True
            )

            paths = options.pop('<path>', None)
            setattr(cls, "destination_path", paths.pop() if paths else None)
            setattr(cls, "source_paths", paths)
            setattr(cls, "options", options)

            for k, v in options.iteritems():
                setattr(cls, k, v)

            GsyncListOptions._GsyncListOptions__initialised = True

        def list(cls):
            return GsyncListOptions

        def __getattr__(cls, name):
            cls.__initialiseClass()
            return getattr(GsyncListOptions, name)[-1]

        def __setattr__(cls, name, value):
            # Substitut option names: --an-option-name for an_option_name
            import re
            name = re.sub(r'^__', "", re.sub(r'-', "_", name))
            listvalue = []

            # Ensure value is converted to a list type for GsyncListOptions
            if isinstance(value, list):
                if value:
                    listvalue = [] + value
                else:
                    listvalue = [ None ]
            else:
                listvalue = [ value ]

            type.__setattr__(GsyncListOptions, name, listvalue)

    # Cleanup this module to prevent tinkering.
    import sys
    module = sys.modules[__name__]
    del module.__dict__['GetGsyncOptionsType']

    return GsyncOptionsType

# Our singlton abstract proxy class.
class GsyncOptions(object):
    __metaclass__ = GetGsyncOptionsType()

type 実際には metaclass -- 別のクラスを作成するクラス。ほとんど metaclass のサブクラスです type. 。の metaclass を受け取ります new class を最初の引数として指定し、以下に示す詳細を含むクラス オブジェクトへのアクセスを提供します。

>>> class MetaClass(type):
...     def __init__(cls, name, bases, attrs):
...         print ('class name: %s' %name )
...         print ('Defining class %s' %cls)
...         print('Bases %s: ' %bases)
...         print('Attributes')
...         for (name, value) in attrs.items():
...             print ('%s :%r' %(name, value))
... 

>>> class NewClass(object, metaclass=MetaClass):
...    get_choch='dairy'
... 
class name: NewClass
Bases <class 'object'>: 
Defining class <class 'NewClass'>
get_choch :'dairy'
__module__ :'builtins'
__qualname__ :'NewClass'

Note:

クラスはどの時点でもインスタンス化されていないことに注意してください。クラスを作成するという単純な行為によって、 metaclass.

TL;DR バージョン

type(obj) 関数はオブジェクトのタイプを取得します。

type() クラスのそれは メタクラス.

メタクラスを使用するには:

class Foo(object):
    __metaclass__ = MyMetaClass

Python クラス自体は、インスタンスと同様に、そのメタクラスのオブジェクトです。

デフォルトのメタクラス。クラスを次のように決定するときに適用されます。

class foo:
    ...

メタ クラスは、クラスのセット全体に何らかのルールを適用するために使用されます。たとえば、データベースにアクセスするための ORM を構築しており、各テーブルのレコードをそのテーブルにマップされたクラス (フィールド、ビジネス ルールなどに基づいて) にしたいとします。これは、メタクラスの使用例です。たとえば、接続プール ロジックは、すべてのテーブルのレコードのすべてのクラスで共有されます。もう 1 つの用途は、複数のクラスのレコードが関与する外部キーをサポートするためのロジックです。

メタクラスを定義すると、タイプをサブクラス化し、次のマジック メソッドをオーバーライドしてロジックを挿入できます。

class somemeta(type):
    __new__(mcs, name, bases, clsdict):
      """
  mcs: is the base metaclass, in this case type.
  name: name of the new class, as provided by the user.
  bases: tuple of base classes 
  clsdict: a dictionary containing all methods and attributes defined on class

  you must return a class object by invoking the __new__ constructor on the base metaclass. 
 ie: 
    return type.__call__(mcs, name, bases, clsdict).

  in the following case:

  class foo(baseclass):
        __metaclass__ = somemeta

  an_attr = 12

  def bar(self):
      ...

  @classmethod
  def foo(cls):
      ...

      arguments would be : ( somemeta, "foo", (baseclass, baseofbase,..., object), {"an_attr":12, "bar": <function>, "foo": <bound class method>}

      you can modify any of these values before passing on to type
      """
      return type.__call__(mcs, name, bases, clsdict)


    def __init__(self, name, bases, clsdict):
      """ 
      called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.
      """
      pass


    def __prepare__():
        """
        returns a dict or something that can be used as a namespace.
        the type will then attach methods and attributes from class definition to it.

        call order :

        somemeta.__new__ ->  type.__new__ -> type.__init__ -> somemeta.__init__ 
        """
        return dict()

    def mymethod(cls):
        """ works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.
        """
        pass

とにかく、これら 2 つは最もよく使用されるフックです。メタクラス化は強力ですが、上記はメタクラス化の使用法の完全なリストには程遠いものです。

type() 関数は、オブジェクトの型を返すことも、新しい型を作成することもできます。

たとえば、type() 関数を使用して Hi クラスを作成できますが、クラス Hi(object) でこの方法を使用する必要はありません。

def func(self, name='mike'):
    print('Hi, %s.' % name)

Hi = type('Hi', (object,), dict(hi=func))
h = Hi()
h.hi()
Hi, mike.

type(Hi)
type

type(h)
__main__.Hi

type() を使用してクラスを動的に作成することに加えて、クラスの作成動作を制御し、メタクラスを使用することもできます。

Python オブジェクト モデルによれば、クラスはオブジェクトであるため、クラスは別の特定のクラスのインスタンスである必要があります。デフォルトでは、Python クラスは type クラスのインスタンスです。つまり、type はほとんどの組み込みクラスのメタクラスであり、ユーザー定義クラスのメタクラスです。

class ListMetaclass(type):
    def __new__(cls, name, bases, attrs):
        attrs['add'] = lambda self, value: self.append(value)
        return type.__new__(cls, name, bases, attrs)

class CustomList(list, metaclass=ListMetaclass):
    pass

lst = CustomList()
lst.add('custom_list_1')
lst.add('custom_list_2')

lst
['custom_list_1', 'custom_list_2']

Magic はメタクラスにキーワード引数を渡したときに有効になり、Python インタプリタに ListMetaclass を通じて CustomList を作成するよう指示します。 新しい () この時点で、たとえばクラス定義を変更し、新しいメソッドを追加して、修正された定義を返すことができます。

公開された回答に加えて、次のことが言えます。 metaclass クラスの動作を定義します。したがって、メタクラスを明示的に設定できます。Python がキーワードを取得するたびに class それから検索を開始します metaclass. 。見つからない場合は、デフォルトのメタクラス タイプを使用してクラスのオブジェクトが作成されます。の使用 __metaclass__ 属性を設定できます metaclass あなたのクラスの:

class MyClass:
   __metaclass__ = type
   # write here other method
   # write here one more method

print(MyClass.__metaclass__)

次のような出力が生成されます。

class 'type'

そしてもちろん、自分で作成することもできます metaclass クラスを使用して作成されたクラスの動作を定義します。

それを行うためのデフォルト metaclass これがメインであるため、型クラスを継承する必要があります metaclass:

class MyMetaClass(type):
   __metaclass__ = type
   # you can write here any behaviour you want

class MyTestClass:
   __metaclass__ = MyMetaClass

Obj = MyTestClass()
print(Obj.__metaclass__)
print(MyMetaClass.__metaclass__)

出力は次のようになります。

class '__main__.MyMetaClass'
class 'type'
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top