6653

Python では、メタクラスとは何ですか? また、それらを何に使用しますか?

4

24 に答える 24

7906

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

メタクラスを理解する前に、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, bases, attrs)

どこ:

  • name: クラスの名前
  • bases: 親クラスのタプル (継承の場合、空にすることができます)
  • attrs: 属性の名前と値を含む辞書

例えば:

>>> 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が実際にはメタクラスであるためです。typePython がバックグラウンドですべてのクラスを作成するために使用するメタクラスです。

ここで、「なぜ小文字で書かれていて、そうではないのTypeか」と疑問に思います。

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

__class__属性を確認するとわかります。

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

>>> 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__属性_

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

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

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

注意してください、それはトリッキーです。

最初に書き込みclass Foo(object)ますが、クラス オブジェクトFooはまだメモリ内に作成されていません。

__metaclass__Python はクラス定義でを探します。見つかった場合は、それを使用してオブジェクト クラスを作成しますFoo。そうでない場合は type、クラスの作成に使用されます。

それを数回読んでください。

あなたがするとき:

class Foo(Bar):
    pass

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

__metaclass__に属性はありますFooか?

Fooはいの場合は、メモリ内にあるものを使用して名前を付けて、メモリ内にクラスオブジェクトを作成します(クラスオブジェクトと言いました。ここにとどまります)__metaclass__

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

まったく見つからない場合は__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 に対して行います。

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

このように、このモジュールのすべてのクラスはこのメタクラスを使用して作成され、メタクラスにすべての属性を大文字にするように指示するだけです。

幸いなことに、__metaclass__実際には任意の callable にすることができ、正式なクラスである必要はありません (名前に「クラス」が含まれているものはクラスである必要はありませんが、役に立ちます)。

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

# 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_attrs):
    """
      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_attrs = {
        attr if attr.startswith("__") else attr.upper(): v
        for attr, v in future_class_attrs.items()
    }

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

__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'

確認しよう:

>>> hasattr(Foo, 'bar')
False
>>> hasattr(Foo, 'BAR')
True
>>> Foo.BAR
'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_attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in future_class_attrs.items()
        }
        return type(future_class_name, future_class_parents, uppercase_attrs)

上記を書き直してみましょう。ただし、変数名の意味がわかったので、より短く、より現実的な変数名を使用します。

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type(clsname, bases, uppercase_attrs)

余分な引数に気付いたかもしれませんcls。特別なことは何もありません__new__。最初のパラメーターとして、定義されているクラスを常に受け​​取ります。selfインスタンスを最初のパラメーターとして受け取る通常のメソッドや、クラス メソッドのクラスを定義する場合と同様です。

しかし、これは適切な OOP ではありません。type直接呼び出しており、親の を​​オーバーライドしたり呼び出したりしていません__new__。代わりにそれをしましょう:

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return type.__new__(cls, clsname, bases, uppercase_attrs)

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

class UpperAttrMetaclass(type):
    def __new__(cls, clsname, bases, attrs):
        uppercase_attrs = {
            attr if attr.startswith("__") else attr.upper(): v
            for attr, v in attrs.items()
        }
        return super(UpperAttrMetaclass, cls).__new__(
            cls, clsname, bases, uppercase_attrs)

ああ、Python 3 では、次のようにキーワード引数を使用してこの呼び出しを行う場合:

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

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

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

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

メタクラスを使用したコードの複雑さの背後にある理由は、メタクラスが原因ではありません。通常、メタクラスを使用して、イントロスペクションに依存したねじれたことを行ったり、継承を操作したり__dict__、 などの変数を操作したりするためです。

実際、メタクラスは黒魔術を行うのに特に役立ち、したがって複雑なことを行います。しかし、それ自体は単純です。

  • クラスの作成を傍受する
  • クラスを変更する
  • 変更されたクラスを返す

関数の代わりにメタクラス クラスを使用するのはなぜですか?

任意の呼び出し可能オブジェクトを受け入れることができるので__metaclass__、明らかにより複雑なクラスを使用するのはなぜですか?

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

  • 意図は明らかです。を読むUpperAttrMetaclass(type)と、次に何が続くかがわかります
  • OOPを使用できます。メタクラスはメタクラスから継承し、親メソッドをオーバーライドできます。メタクラスはメタクラスを使用することさえできます。
  • metaclass-class を指定し、metaclass-function を指定しなかった場合、クラスのサブクラスはそのメタクラスのインスタンスになります。
  • コードをより適切に構成できます。上記の例のように些細なことにメタクラスを使用することは決してありません。それは通常、複雑なもののためです。複数のメソッドを作成して 1 つのクラスにグループ化できる機能は、コードを読みやすくするのに非常に役立ちます。
  • __new____init__およびにフックできます__call__。これにより、さまざまなことを行うことができます。通常は ですべて実行できますが、__new__を使用する方が快適な人もい__init__ます。
  • これらはメタクラスと呼ばれます。何か意味があるに違いない!

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

今、大きな問題です。エラーが発生しやすいあいまいな機能を使用するのはなぜですか?

通常、次のことは行いません。

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

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

メタクラスの主な使用例は、API の作成です。この典型的な例は Django ORM です。次のようなものを定義できます。

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

しかし、これを行うと:

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

IntegerFieldオブジェクトは返されません。を返しint、データベースから直接取得することもできます。

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

Django は、単純な API を公開し、メタクラスを使用して複雑なものを単純に見せ、この API からコードを再作成して、舞台裏で実際の仕事を行います。

最後の言葉

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

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

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

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

を除いてtype

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

第二に、メタクラスは複雑です。非常に単純なクラスの変更には使用したくない場合があります。次の 2 つの異なる手法を使用して、クラスを変更できます。

クラスの変更が必要な場合は 99% の確率で、これらを使用することをお勧めします。

しかし、98% の確率で、クラスの変更はまったく必要ありません。

于 2011-07-05T11:29:50.927 に答える
3342

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

Python では、( Jerubが示すように) メタクラスに任意の callable を使用できますが、より良いアプローチは、それを実際のクラス自体にすることです。typePython の通常のメタクラスです。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__
于 2008-09-19T07:01:58.623 に答える
455

この回答は 2008 年に作成された Python 2.x に対するものであり、メタクラスは 3.x ではわずかに異なります。

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

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

メタクラスは 3 つの引数を取ります。「name」、「bases」、および「dict

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

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

' class: ' がそれを呼び出す方法を示すメタクラスを定義しましょう。

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

Initialisedメタクラスを持つことによって得られる魔法の振る舞いinit_attributesは、 のサブクラスには渡されないことに注意してくださいInitialised

これはさらに具体的な例で、「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
于 2008-09-19T06:26:10.537 に答える
210

他の人は、メタクラスがどのように機能し、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

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

于 2011-06-21T16:30:26.837 に答える
187

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

たとえば、Django モデルを見ると、その定義は少しわかりにくいように見えます。クラス プロパティのみを定義しているように見えます。

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

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

于 2008-09-19T06:45:40.020 に答える
150

メタクラス プログラミングの 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% であるということです。

于 2008-09-19T06:32:58.397 に答える
137

メタクラスとは それらを何に使用しますか?

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)a の適切なテストがあることがわかります - 。型クラスのクラス インスタンスの次の単純な実装は、クラスのデフォルトを改善する可能性のあるデモを提供します。__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__、コマンド ラインで echoed を実行すると、デフォルトよりもはるかに見苦しくなくなります。

>>> 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__名前空間

たとえば、クラスのメソッドが作成される順序を知りたい場合は、クラスの名前空間として順序付けられた dict を提供できます。Python 3 で実装されている場合、クラスの名前空間 dict__prepare__を返すこれを使用してこれを行います。

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>})
于 2015-08-10T23:28:09.000 に答える
89

__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__()メソッドは、クラスのインスタンスが callable として使用されるときに呼び出されます。しかし、以前の回答からわかるように、クラス自体はメタクラスのインスタンスであるため、クラスを呼び出し可能として使用するとき (つまり、そのインスタンスを作成するとき) は、実際にはそのメタクラスの__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.

上記のコードは、実際にはタスクをログに記録する以上のことをしていないことに注意してください。各メソッドは、実際の作業をその親の実装に委譲するため、デフォルトの動作が維持されます。typeisMeta_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
于 2016-10-13T09:21:26.067 に答える
71

メタクラスは、他のクラスを作成する方法を示すクラスです。

これは、メタクラスを問題の解決策と見なしたケースです。非常に複雑な問題があり、おそらく別の方法で解決できたはずですが、メタクラスを使用して解決することにしました。複雑なため、モジュール内のコメントが記述されたコードの量を上回っている、私が記述した数少ないモジュールの 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()
于 2014-02-24T21:20:49.270 に答える
56

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

>>> 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.

于 2016-08-09T18:49:44.417 に答える
39

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 つは最も一般的に使用されるフックです。メタクラス化は強力であり、上記はメタクラス化の用途の完全なリストではありません。

于 2017-07-13T07:58:10.633 に答える
25

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

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

print(MyClass.__metaclass__)

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

class 'type'

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

これを行うには、これが main であるため、デフォルト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'
于 2018-09-15T12:41:20.950 に答える
17

__init_subclass__(cls, **kwargs)Python 3.6 では、メタクラスの多くの一般的な使用例を置き換えるために、新しい dunder メソッドが導入されたことに注意してください。Is は、定義クラスのサブクラスが作成されるときに呼び出されます。Python ドキュメントを参照してください。

于 2020-03-03T10:06:52.060 に答える
15

これが何に使用できるかの別の例を次に示します。

  • を使用しmetaclassて、そのインスタンス (クラス) の機能を変更できます。
class MetaMemberControl(type):
    __slots__ = ()

    @classmethod
    def __prepare__(mcs, f_cls_name, f_cls_parents,  # f_cls means: future class
                    meta_args=None, meta_options=None):  # meta_args and meta_options is not necessarily needed, just so you know.
        f_cls_attr = dict()
        if not "do something or if you want to define your cool stuff of dict...":
            return dict(make_your_special_dict=None)
        else:
            return f_cls_attr

    def __new__(mcs, f_cls_name, f_cls_parents, f_cls_attr,
                meta_args=None, meta_options=None):

        original_getattr = f_cls_attr.get('__getattribute__')
        original_setattr = f_cls_attr.get('__setattr__')

        def init_getattr(self, item):
            if not item.startswith('_'):  # you can set break points at here
                alias_name = '_' + item
                if alias_name in f_cls_attr['__slots__']:
                    item = alias_name
            if original_getattr is not None:
                return original_getattr(self, item)
            else:
                return super(eval(f_cls_name), self).__getattribute__(item)

        def init_setattr(self, key, value):
            if not key.startswith('_') and ('_' + key) in f_cls_attr['__slots__']:
                raise AttributeError(f"you can't modify private members:_{key}")
            if original_setattr is not None:
                original_setattr(self, key, value)
            else:
                super(eval(f_cls_name), self).__setattr__(key, value)

        f_cls_attr['__getattribute__'] = init_getattr
        f_cls_attr['__setattr__'] = init_setattr

        cls = super().__new__(mcs, f_cls_name, f_cls_parents, f_cls_attr)
        return cls


class Human(metaclass=MetaMemberControl):
    __slots__ = ('_age', '_name')

    def __init__(self, name, age):
        self._name = name
        self._age = age

    def __getattribute__(self, item):
        """
        is just for IDE recognize.
        """
        return super().__getattribute__(item)

    """ with MetaMemberControl then you don't have to write as following
    @property
    def name(self):
        return self._name

    @property
    def age(self):
        return self._age
    """


def test_demo():
    human = Human('Carson', 27)
    # human.age = 18  # you can't modify private members:_age  <-- this is defined by yourself.
    # human.k = 18  # 'Human' object has no attribute 'k'  <-- system error.
    age1 = human._age  # It's OK, although the IDE will show some warnings. (Access to a protected member _age of a class)

    age2 = human.age  # It's OK! see below:
    """
    if you do not define `__getattribute__` at the class of Human,
    the IDE will show you: Unresolved attribute reference 'age' for class 'Human'
    but it's ok on running since the MetaMemberControl will help you.
    """


if __name__ == '__main__':
    test_demo()

metaclass強力で、さまざまなことができます (モンキー マジックなど)。

于 2019-12-20T11:03:31.263 に答える