【问题标题】:What are metaclasses in Python?Python 中的元类是什么?
【发布时间】:2013-04-28 22:50:18
【问题描述】:

在 Python 中,什么是元类,我们用它们做什么?

【问题讨论】:

标签: python oop metaclass python-class python-datamodel


【解决方案1】:

看这个:

Python 3.10.0rc2 (tags/v3.10.0rc2:839d789, Sep  7 2021, 18:51:45) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Object:
...     pass
... 
>>> class Meta(type):
...     test = 'Worked!!!'
...     def __repr__(self):
...             return 'This is "Meta" metaclass'
... 
>>> class ObjectWithMetaClass(metaclass=Meta):
...     pass
... 
>>> Object or type(Object())
<class '__main__.Object'>
>>> ObjectWithMetaClass or type(ObjectWithMetaClass())
This is "Meta" metaclass
>>> Object.test
AttributeError: ...
>>> ObjectWithMetaClass.test
'Worked!!!'
>>> type(Object)
<class 'type'>
>>> type(ObjectWithMetaClass)
<class '__main__.Meta'>
>>> type(type(ObjectWithMetaClass))
<class 'type'>
>>> Object.__bases__
(<class 'object'>,)
>>> ObjectWithMetaClass.__bases__
(<class 'object'>,)
>>> type(ObjectWithMetaClass).__bases__
(<class 'type'>,)
>>> Object.__mro__
(<class '__main__.Object'>, <class 'object'>)
>>> ObjectWithMetaClass.__mro__
(This is "Meta" metaclass, <class 'object'>)
>>> 

换句话说,当一个对象没有被创建时(对象的类型),我们寻找的是 MetaClass。

【讨论】:

    【解决方案2】:

    最佳答案是正确的

    但是读者可能会来这里寻找关于类似名称的内部类的答案。它们存在于流行的库中,例如 DjangoWTForms

    正如 DavidW 在此答案下方的 cmets 中指出的那样,这些是 特定于库的 功能,请勿与高级、无关的 Python 语言混淆具有相似名称的功能

    相反,这些是类字典中的命名空间。为了便于阅读,它们是使用内部类构造的。

    在此示例特殊字段中,abstract 明显与 Author 模型的字段分开。

    from django.db import models
    
    class Author(models.Model):
        name = models.CharField(max_length=50)
        email = models.EmailField()
    
        class Meta:
            abstract = True
    

    另一个例子来自WTForms的文档:

    from wtforms.form import Form
    from wtforms.csrf.session import SessionCSRF
    from wtforms.fields import StringField
    
    class MyBaseForm(Form):
        class Meta:
            csrf = True
            csrf_class = SessionCSRF
    
        name = StringField("name")
    

    此语法在 python 编程语言中没有得到特殊处理。 Meta 不是这里的关键字,也不会触发元类行为。相反,DjangoWTForms 等包中的第三方库代码会在某些类的构造函数和其他地方读取此属性。

    这些声明的存在修改了具有这些声明的类的行为。例如,WTForms 读取 self.Meta.csrf 以确定表单是否需要 csrf 字段。

    【讨论】:

    • 这是 Django 特有的功能,其中名为 Meta 的嵌套类具有特殊含义。问题是关于具有相似名称的不相关 Python 语言功能。
    • @DavidW — hamilyon 对这篇文章进行了英勇的编辑。现在,在我看来,这是一个非常有用的答案。
    • @AlexWaygood 我可能会拒绝编辑(更改太大......)但我可以看到它确实澄清了一些令人困惑的事情,所以它可能很有用。考虑到这一点,我删除了我的反对票。
    • @DavidW 是的,我认为您可以双向争论。我通常不会批准这么大的编辑。但我觉得它保持了原始帖子的精神,而且似乎相当多的工作已经投入到一项崇高的努力中(澄清一个合理的混淆点),所以决定批准​​。
    【解决方案3】:

    类作为对象

    在了解元类之前,您需要掌握 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可以将类的描述作为参数, 并返回一个类。

    (我知道,根据你传递给它的参数,同一个函数可以有两种完全不同的用途,这是愚蠢的。这是由于落后的问题 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 实际上是一个元类。 type 是 Python 使用元类在幕后创建所有类。

    现在你想知道“为什么它是小写的,而不是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 还在记忆中。

    Python 将在类定义中查找__metaclass__。如果它找到了, 它将使用它来创建对象类Foo。如果没有,它将使用 type 创建类。

    多读几遍。

    当你这样做时:

    class Foo(Bar):
        pass
    

    Python 执行以下操作:

    Foo 中是否有 __metaclass__ 属性?

    如果是,请使用__metaclass__ 中的内容在内存中创建一个名为Foo 的类对象(我说的是类对象)。

    如果 Python 找不到 __metaclass__,它将在 MODULE 级别寻找 __metaclass__,并尝试做同样的事情(但仅限于不继承任何东西的类,基本上是旧式类) .

    如果它根本找不到任何__metaclass__,它将使用Bar(第一个父级)自己的元类(可能是默认的type)来创建类对象。

    这里注意__metaclass__属性不会被继承,父类(Bar.__class__)的元类会被继承。如果Bar 使用__metaclass__ 属性创建Bartype()(而不是type.__new__()),子类将不会继承该行为。

    现在最大的问题是,__metaclass__ 可以输入什么?

    答案是可以创建类的东西。

    什么可以创建一个类? type,或任何子类或使用它的东西。

    Python 3 中的元类

    在 Python 3 中设置元类的语法已更改:

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

    即不再使用__metaclass__ 属性,取而代之的是基类列表中的关键字参数。

    但是元类的行为仍然是largely the same

    在 Python 3 中添加到元类的一件事是,您还可以将属性作为关键字参数传递给元类,如下所示:

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

    阅读以下部分,了解 Python 如何处理此问题。

    自定义元类

    元类的主要目的是自动改变类, 什么时候创建的。

    您通常为 API 执行此操作,您希望在其中创建与 当前上下文。

    想象一个愚蠢的例子,你决定模块中的所有类 应该将它们的属性写成大写。有几种方法可以 这样做,但一种方法是在模块级别设置__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_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):
        ...
    

    它在元类中转换为 this 以使用它:

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

    就是这样。元类真的没有什么更多了。

    使用元类的代码复杂性背后的原因不是因为 元类,这是因为您通常使用元类来做扭曲的事情 依靠自省,操纵继承,vars如__dict__

    确实,元类对于执行黑魔法特别有用,因此 复杂的东西。但它们本身很简单:

    • 拦截类创建
    • 修改类
    • 返回修改后的类

    为什么要使用元类类而不是函数?

    既然__metaclass__ 可以接受任何可调用的,你为什么要使用一个类 因为它显然更复杂?

    这样做有几个原因:

    • 意图很明确。当你读到UpperAttrMetaclass(type),你就知道 接下来会发生什么
    • 您可以使用 OOP。元类可以继承元类,覆盖父方法。元类甚至可以使用元类。
    • 如果您指定了元类类,但不使用元类函数,则类的子类将是其元类的实例。
    • 您可以更好地构建代码。您永远不会将元类用于像上面的示例这样微不足道的事情。它通常用于复杂的事情。能够创建多个方法并将它们分组到一个类中对于使代码更易于阅读非常有用。
    • 您可以连接__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 中重现,并通过在实现中作弊来完成 级别。

    其次,元类很复杂。您可能不想将它们用于 非常简单的类更改。您可以使用两种不同的技术更改类:

    99% 的情况下,您需要更改班级,最好使用这些。

    但在 98% 的情况下,您根本不需要更改班级。

    【讨论】:

    • 似乎在 Django models.Model 中它不使用 __metaclass__ 而是使用 class Model(metaclass=ModelBase): 来引用 ModelBase 类,然后该类执行上述元类魔术。好帖子!这是 Django 源代码:github.com/django/django/blob/master/django/db/models/…
    • __metaclass__属性不会被继承,父类(Bar.__class__)的元类会被继承。如果Bar 使用__metaclass__ 属性创建Bartype()(而不是type.__new__()),子类将不会继承该行为。>> -- 你/有人请解释一下这段话?
    • @MaxGoodridge 这是元类的 Python 3 语法。见Python 3.6 Data model VS Python 2.7 Data model
    • Now you wonder why the heck is it written in lowercase, and not Type? - 因为它是用 C 实现的 - 这与 defaultdict 是小写而 OrderedDict(在 python 2 中)是正常的 CamelCase 的原因相同
    • 这是一个社区 wiki 答案(因此,那些提出更正/改进意见的人可能会考虑将他们的 cmets 编辑到答案中,如果他们确定他们是正确的)。
    【解决方案4】:

    我在一个名为classutilities 的包中看到了一个有趣的元类用例。它检查所有类变量是否都是大写格式(便于对配置类进行统一的逻辑),并检查类中是否没有实例级方法。 Metaclases 的另一个有趣示例是基于复杂条件(检查多个环境变量的值)停用单元测试。

    【讨论】:

      【解决方案5】:

      在 Python 中,元类是子类的子类,它决定子类的行为方式。一个类是另一个元类的一个实例。在 Python 中,类指定类的实例的行为方式。

      由于元类负责类的生成,您可以编写自己的自定义元类,通过执行额外的操作或注入代码来更改类的创建方式。自定义元类并不总是很重要,但它们可能很重要。

      【讨论】:

        【解决方案6】:

        元类是一种类,它定义了类的行为方式,或者我们可以说一个类本身就是一个元类的实例。

        【讨论】:

        • 请添加相关信息..您的 cmets 令人困惑
        【解决方案7】:

        请注意,在 python 3.6 中,引入了一个新的 dunder 方法 __init_subclass__(cls, **kwargs) 来替换元类的许多常见用例。 Is 在定义类的子类创建时调用。见python docs

        【讨论】:

          【解决方案8】:

          在 Python 中,类是一个对象,就像任何其他对象一样,它是“某物”的一个实例。这个“东西”就是所谓的元类。这个元类是一种特殊类型的类,它创建其他类的对象。因此,元类负责创建新类。这允许程序员自定义生成类的方式。

          要创建元类,通常会覆盖 new() 和 init() 方法。 new() 可以被覆盖来改变对象的创建方式,而 init() 可以被覆盖来改变初始化对象的方式。元类可以通过多种方式创建。其中一种方法是使用 type() 函数。 type() 函数,当使用 3 个参数调用时,会创建一个元类。参数是:-

          1. 类名
          2. 具有由类继承的基类的元组
          3. 包含所有类方法和类变量的字典

          创建元类的另一种方法包括“元类”关键字。将元类定义为一个简单的类。在继承类的参数中,传递metaclass=metaclass_name

          元类可以专门用于以下情况:-

          1. 必须将特定效果应用于所有子类时
          2. 需要自动更改类(创建时)
          3. API 开发人员

          【讨论】:

            【解决方案9】:

            这是另一个可以用来做什么的例子:

            • 您可以使用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 很强大,你可以用它做很多事情(比如猴子魔法),但要小心,这可能只有你自己知道。

            【讨论】:

              【解决方案10】:

              tl;dr 版本

              type(obj) 函数获取对象的类型。

              一个类的type() 是它的元类

              使用元类:

              class Foo(object):
                  __metaclass__ = MyMetaClass
              

              type 是它自己的元类。类的类是元类——类的主体是传递给用于构造类的元类的参数。

              Here您可以阅读有关如何使用元类来自定义类构造的信息。

              【讨论】:

                【解决方案11】:

                请注意,此答案适用于 Python 2.x,因为它是在 2008 年编写的,元类在 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'
                

                现在,一个真正有意义的例子,这将自动使列表中的变量“属性”设置在类上,并设置为无。

                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
                

                【讨论】:

                  【解决方案12】:

                  在面向对象的编程中,元类是一个类,其实例是类。正如普通类定义某些对象的行为一样,元类定义某些类及其实例的行为 元类一词仅表示用于创建类的东西。换句话说,它是一个类的类。元类用于创建类,就像对象是类的实例一样,类是元类的实例。在 python 中,类也被视为对象。

                  【讨论】:

                  • 与其给出书呆子的定义,如果你添加一些例子会更好。您答案的第一行似乎是从元类的维基百科条目中复制的。
                  • @verisimilitude 我也在学习你能否通过提供一些你的经验中的实际例子来帮助我改进这个答案??
                  【解决方案13】:

                  元类是类的类。类定义类的实例(即对象)的行为方式,而元类定义类的行为方式。类是元类的一个实例。

                  虽然在 Python 中您可以对元类使用任意可调用对象(如 Jerub 所示),但更好的方法是使其本身成为实际类。 type 是 Python 中常用的元类。 type 本身就是一个类,它是它自己的类型。您将无法纯粹在 Python 中重新创建像 type 这样的东西,但 Python 会作弊。要在 Python 中创建自己的元类,您真的只想继承 type

                  元类最常用作类工厂。当您通过调用类创建对象时,Python 通过调用元类创建一个新类(当它执行“类”语句时)。结合普通的 __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__
                  

                  【讨论】:

                  • class A(type):pass&lt;NEWLINE&gt;class B(type,metaclass=A):pass&lt;NEWLINE&gt;b.__class__ = b
                  • ppperry 他显然的意思是如果不将类型本身用作元类,就无法重新创建类型。可以这么说。
                  • Example 类的实例不应该调用 unregister() 吗?
                  • 请注意,__metaclass__ 在 Python 3 中不受支持。在 Python 3 中使用 class MyObject(metaclass=MyType),请参阅python.org/dev/peps/pep-3115 和下面的答案。
                  • 文档描述了how the metaclass is chosen。元类不是继承的,而是派生的。如果您指定一个元类,它必须是每个基类元类的子类型;否则,您将使用作为其他基类元类的子类型的基类元类。注意,有可能no找到有效的元类,定义会失败。
                  【解决方案14】:

                  除了已发布的答案,我可以说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'
                  

                  【讨论】:

                    【解决方案15】:

                    创建类实例时元类__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
                    

                    【讨论】:

                    • 这是对先前赞成的“接受的答案”的一个很好的补充。它为中级编码人员提供了示例。
                    【解决方案16】:

                    我认为元类编程的 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 中,类也需要是一流的对象才能启用此行为。

                    我自己从来没有写过,但我认为元类最好的用途之一可以在Django framework 中看到。模型类使用元类方法来启用编写新模型或表单类的声明式风格。在元类创建类时,所有成员都可以自定义类本身。

                    剩下要说的是:如果您不知道元类是什么,那么您不需要它们的概率是 99%。

                    【讨论】:

                      【解决方案17】:

                      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是大部分内置类的元类和用户自定义类的元类。

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

                      当我们在 metaclass 中传递关键字参数时,Magic 将生效,它指示 Python 解释器通过 ListMetaclass 创建 CustomList。 new(),此时我们可以修改类定义,例如,添加一个新方法,然后返回修改后的定义。

                      【讨论】:

                        【解决方案18】:

                        什么是元类?你用它们做什么?

                        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
                          
                        • 第三种方式,元类是类的类。

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

                        当您编写类定义并且 Python 执行它时,它会使用元类来实例化类对象(反过来,该类对象将用于实例化该类的实例)。

                        正如我们可以使用类定义来改变自定义对象实例的行为方式一样,我们可以使用元类类定义来改变类对象的行为方式。

                        它们可以用来做什么?来自docs

                        元类的潜在用途是无限的。已经探索的一些想法包括日志记录、接口检查、自动委托、自动属性创建、代理、框架和自动资源锁定/同步。

                        尽管如此,通常鼓励用户避免使用元类,除非绝对必要。

                        每次创建类时都使用元类:

                        当你写一个类定义时,例如,像这样,

                        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__ 存在是因为我们没有定义 @987654347 @ - 如果我们 define __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 对象时可以做的最有价值的事情之一就是为其提供良好的__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__returns the namespace dict for the class if it is implemented in 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')
                        

                        请注意,此示例改编自 documentation - 新的 enum in the standard library 执行此操作。

                        所以我们所做的就是通过创建一个类来实例化一个元类。我们也可以像对待任何其他类一样对待元类。它有一个方法解析顺序:

                        >>> 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>})
                        

                        【讨论】:

                          【解决方案19】:

                          type 实际上是一个metaclass——一个创建另一个类的类。 大多数metaclasstype 的子类。 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的执行。

                          【讨论】:

                            【解决方案20】:

                            Python 类本身就是它们的元类的对象(例如实例)。

                            默认元类,当您将类确定为时应用:

                            class foo:
                                ...
                            

                            元类用于将某些规则应用于整个类集。例如,假设您正在构建一个 ORM 来访问数据库,并且您希望每个表中的记录属于映射到该表的类(基于字段、业务规则等),这可能是元类的使用例如,连接池逻辑,由所有表中的所有记录类共享。另一个用途是支持外键的逻辑,它涉及多类记录。

                            当您定义元类时,您可以子类化类型,并且可以覆盖以下魔术方法来插入您的逻辑。

                            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
                            

                            无论如何,这两个是最常用的钩子。元分类很强大,上面还没有详尽列出元分类的用途。

                            【讨论】:

                              【解决方案21】:

                              其他人已经解释了元类的工作原理以及它们如何适应 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,该属性记录了定义类的顺序。

                              【讨论】:

                              • 感谢您的示例。为什么你发现这比从 MyBase 继承更容易,其 __init__(self)type(self)._order = MyBase.counter; MyBase.counter += 1
                              • 我希望对类本身而不是它们的实例进行编号。
                              • 对,呵呵。谢谢。我的代码将在每次实例化时重置 MyType 的属性,并且如果从未创建 MyType 的实例,则永远不会设置该属性。哎呀。 (并且类属性也可以工作,但与元类不同,它没有提供明显的位置来存储计数器。)
                              • 这是一个非常有趣的例子,尤其是因为人们可以真正理解为什么需要一个元类来为特定的困难提供解决方案。 OTOH,我很难相信任何人都真的需要按照定义类的顺序来实例化对象:我想我们只需要相信你的话:)。
                              • 它是一个文档测试框架,类是要测试的特定文件、要运行的测试等的声明性描述。该框架在一份格式良好的报告中报告了这些结果,该报告按产品、文档和测试分组。如果测试以可预测的顺序运行,则该报告会更有用。 :-)
                              【解决方案22】:

                              Python 3 更新

                              (此时)元类中有两个关键方法:

                              • __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)
                              

                              一个简单的例子:

                              假设您希望在属性上运行一些简单的验证代码——比如它必须始终是 intstr。如果没有元类,您的类将如下所示:

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

                              如您所见,您必须重复两次属性名称。这使得拼写错误和恼人的错误成为可能。

                              一个简单的元类可以解决这个问题:

                              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
                              

                              【讨论】:

                              • 请注意,从 python 3.6 开始,您可以在描述符 (ValidateType) 中使用 __set_name__(cls, name) 来设置描述符中的名称 (self.name,在这种情况下还可以使用 self.attr)。添加此功能是为了不必深入研究此特定常见用例的元类(请参阅 PEP 487)。
                              【解决方案23】:

                              元类是一个告诉(某些)其他类应该如何创建的类。

                              在这种情况下,我将元类视为解决问题的方法: 我有一个非常复杂的问题,可能可以用不同的方式解决,但我选择使用元类来解决它。由于复杂性,它是我编写的少数几个模块之一,其中模块中的 cmets 超过了已编写的代码量。在这里……

                              #!/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()
                              

                              【讨论】:

                                【解决方案24】:

                                元类的一个用途是自动向实例添加新的属性和方法。

                                例如,如果您查看Django models,他们的定义看起来有点混乱。看起来好像您只是在定义类属性:

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

                                但是,在运行时,Person 对象充满了各种有用的方法。请参阅 source 了解一些惊人的元分类。

                                【讨论】:

                                • 使用元类不是为而不是实例添加新的属性和方法吗?据我了解,元类改变了类本身,因此实例可以由改变的类以不同的方式构造。对于试图了解元类性质的人来说可能有点误导。在实例上拥有有用的方法可以通过正常的继承来实现。不过,以 Django 代码为例的参考很好。
                                猜你喜欢
                                • 2017-02-14
                                • 2011-02-10
                                相关资源
                                最近更新 更多